Python Dict键作为类中的函数

Python Dict键作为类中的函数,python,Python,如何在下面的代码中从字典中调用get_productname函数 test = { 'get_productname' : { 'id' : 1, 'active' : 1, } } class search(object): def __init__(self): for key, value in

如何在下面的代码中从字典中调用get_productname函数

test = {
       'get_productname' : {
                         'id' : 1,
                         'active' : 1,
                         }
    }

class search(object):
    def __init__(self):
        for key, value in test.items():
            if test[key]['active']:
                ... here i want to call the "get_productname" function from the dict key name
                self.key()
                ... HOW CAN I DO THIS?

    def get_productname(self, id):
        ...
        return productname 

如果您事先知道要调用的方法属于哪些类,那么可以使用这些方法本身而不是它们的名称作为字典键。然后你可以简单地称之为:

class search(object):
    def __init__(self, test):
        for func, value in test.iteritems():
            if value['active']:
                func(self, value['id'])
    def get_productname(self, id):
        pass

test = {search.get_productname: {'id' : 1, 'active' : 1}}

您需要
getattr
函数

class search(object):
  def __init__(self):
    for key, value in test.items():
      if test[key]['active']:
        getattr(self, key)(test['key']['id'])
根据注释,如果您不是100%肯定该方法将存在,您可以提前执行
hasattr(self,name)
检查,但这相当于:

try:
  getattr(self, key)
except AttributeError, e:
  # code here that would handle a missing method.

假设您在某个地方定义了一个
get\u productname()
函数,我会将其添加到字典中,如下所示:

test = {
       'get_productname' : {
                         'id' : 1,
                         'active' : 1,
                         'func' : get_productname
                         }
    }
class search(object):
    def __init__(self):
        for key, value in test.items():
            if test[key]['active']:
                # then call the associated function like this
                test[key]['func']()
                ...
那么你可以这样称呼它:

test = {
       'get_productname' : {
                         'id' : 1,
                         'active' : 1,
                         'func' : get_productname
                         }
    }
class search(object):
    def __init__(self):
        for key, value in test.items():
            if test[key]['active']:
                # then call the associated function like this
                test[key]['func']()
                ...

希望这能有所帮助。

尽管人们可能会因为我的建议而批评我:

试试这个:

test = {
       'get_productname' : {
                         'id' : 1,
                         'active' : 1,
                         }
    }

class search(object):
    def __init__(self):
        for key, value in test.items():
            if test[key]['active']:
                eval("self.%s()" % key)
                # or, if you want to pass ID as an arg:
                eval("self.%(method_name)s(id=%(id)s)" % \
                      dict(method_name=key, id=value["id"])

    def get_productname(self, id):
        ...
        return productname 

还没有运行它,但应该可以运行。

确保该方法存在的最佳方法是尝试
getattr
并捕获
AttributeError
——这就是
hasattr
所做的!您也可以只使用
getattr(self,key,None)
(如果函数不存在,则将
None
替换为您想要获得的任何默认值)。嗯,不必担心。在这种情况下,上面的getattr建议似乎是更好的用法。尽可能避免评估当然,std免责声明。