看哪,我的简单的类:我怎么能动态地引用变量在Python
import sys
class Foo(object):
def __init__(self):
self.frontend_attrs = ['name','ip_address','mode','port','max_conn']
self.backend_attrs = ['name','balance_method','balance_mode']
init方法上面创建了两个名单,我想动态是指他们两个:
def sanity_check_data(self):
self.check_section('frontend')
self.check_section('backend')
def check_section(self, section):
# HERE IS THE DYNAMIC REFERENCE
for attr in ("self.%s_attrs" % section):
print attr
但当我这样做时,python会抱怨("self.%s_attrs" % section)
的调用。
我读过有关使用get_attr
动态发现模块人...
getattr(sys.modules[__name__], "%s_attrs" % section)()
可这对词典进行。
你想'GETATTR(自我,“{} _attrs” .format(section))' – dano 2014-10-02 15:51:22
真的,你不应该把数据保存在变量名中。这只是要求麻烦。你应该将这两本字典保存在另一个结构中,甚至可以是另一本字典。 – TheSoundDefense 2014-10-02 15:52:23
谢谢@TheSoundDefense的建议,我会把它带上船! – stephenmurdoch 2014-10-02 15:59:05