如何在Python中动态引用变量

ste*_*och 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']
Run Code Online (Sandbox Code Playgroud)

上面的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
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,python抱怨打电话给("self.%s_attrs" % section).

我读过有关人们使用get_attr动态查找模块的信息......

getattr(sys.modules[__name__], "%s_attrs" % section)()
Run Code Online (Sandbox Code Playgroud)

这可以用于词典.

Mic*_*ler 5

我想你要找的是getattr().像这样的东西:

def check_section(self, section):
    for attr in getattr(self, '%s_attrs' % section):
        print attr
Run Code Online (Sandbox Code Playgroud)

虽然在特定情况下,你可能最好使用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
Run Code Online (Sandbox Code Playgroud)