如何在Python中动态引用变量

时间:2014-10-02 15:48:35

标签: 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 个答案:

答案 0 :(得分:5)

我想要的是getattr()。像这样:

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

虽然在特定情况下,你可能最好使用dict,只是为了简单起见:

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