2014-10-02 74 views
2

看哪,我的简单的类:我怎么能动态地引用变量在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)() 

可这对词典进行。

+1

你想'GETATTR(自我,“{} _attrs” .format(section))' – dano 2014-10-02 15:51:22

+1

真的,你不应该把数据保存在变量名中。这只是要求麻烦。你应该将这两本字典保存在另一个结构中,甚至可以是另一本字典。 – TheSoundDefense 2014-10-02 15:52:23

+0

谢谢@TheSoundDefense的建议,我会把它带上船! – stephenmurdoch 2014-10-02 15:59:05

回答

4

你在找什么我认为是getattr()。事情是这样的:

def check_section(self, section): 
    for attr in getattr(self, '%s_attrs' % section): 
     print attr 

虽然与该特定情况下,你可能会用的字典更好,只是为了让事情变得简单:

class Foo(object): 

    def __init__(self): 
    self.my_attrs = { 
     'frontend': ['name','ip_address','mode','port','max_conn'], 
     'backend': ['name','balance_method','balance_mode'], 
    } 

    def sanity_check_data(self): 
    self.check_section('frontend') 
    self.check_section('backend') 

    def check_section(self, section): 
    # maybe use self.my_attrs.get(section) and add some error handling? 
    my_attrs = self.my_attrs[section] 
    for attr in my_attrs: 
     print attr 
+0

呜!它完美的作品。非常感谢! – stephenmurdoch 2014-10-02 15:58:25

+0

很高兴帮助!如果您点击柜台旁边的支票图标,那么它会将该问题标记为解决该特定答案。 – 2014-10-02 16:02:10

+0

特别感谢在结束位! – stephenmurdoch 2014-10-02 16:02:24