动态分配给 class 个变量
Dynamic assignment to class variables
所以我正在使用一个函数来停止在任何地方复制 + Pasta 代码,它具有完全相同的用途减去我希望显示异常的错误消息,但我希望能够访问和设置 class Django 解析的动态变量。
例如:
我知道如果你输入 vars()['{}'.format(a_variable)] 只要变量被命名,你就可以访问它。但是你如何做到这一点呢?
下面的代码不起作用,但概述了如果实例有类似 vars() 的函数或随机的 way/better 方法,我想实现的目标:
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
提前致谢!
感谢@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
所以我正在使用一个函数来停止在任何地方复制 + Pasta 代码,它具有完全相同的用途减去我希望显示异常的错误消息,但我希望能够访问和设置 class Django 解析的动态变量。
例如: 我知道如果你输入 vars()['{}'.format(a_variable)] 只要变量被命名,你就可以访问它。但是你如何做到这一点呢? 下面的代码不起作用,但概述了如果实例有类似 vars() 的函数或随机的 way/better 方法,我想实现的目标:
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
提前致谢!
感谢@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