动态分配给类变量

时间:2015-02-16 22:24:24

标签: django python-2.7 django-models

所以我正在使用一个函数来阻止Copy + Pasta代码到处都有完全相同的用法减去我想要显示异常的错误消息,但是我希望能够动态访问和设置类变量Django解析。

例如: 我知道如果你提供变量()['{}'。format(a_variable)],只要变量被命名,你就可以访问它。但是你如何为实例做到这一点? 下面的代码不起作用,但概述了我想要实现的内容,如果有一个vars()类似于实例的函数或随机的方式/更好的方法:

class test(object):
    max_length = 10
    text = 'blah'
    name = 'hrrrnngg'

    def set_name(self, text):
        self.name = self._parse_text(text, 'name')

    def set_text(self, text):
        self.text = self._parse_text(text, 'text')

    def _parse_text(self, data, variable):
        # a simple idea, but much exception coding in here, i.e. negatives, ranges e.t.c.
        if len(data) + len(vars()['self.{}'.format(variable)]) > self.max_length:
            print "You have failed this city"
        else:
            return "{}, {}".format(vars()['self.{}'.format(variable)], data)

a = test()
print a.text
a.set_text('moo')
print a.text

提前致谢!

1 个答案:

答案 0 :(得分:0)

感谢@jonrsharpe 更正的代码是:

class test(object):
    max_length = 10
    name = 'batman'
    text = 'blah'

    def set_name(self, text):
        self.name = self._parse_text(text, 'name')

    def set_text(self, text):
        self.text = self._parse_text(text, 'text')

    def _parse_text(self, data, variable):
        if len(data) + len(getattr(self, str(variable))) > self.max_length:
            print "You have failed this city"
            return getattr(self, str(variable))
        else:
            return getattr(self, str(variable)) + data


a = test()
print a.text
a.set_text('moo')
print a.text
a.set_text('derppphard')
print a.text

此代码打印到控制台:

$ blah
$ blahmoo
$ You have failed this city
$ blahmoo