Dict键作为类中的函数

pkd*_*dkk 2 python

如何在下面的代码中从字典中调用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 
Run Code Online (Sandbox Code Playgroud)

g.d*_*d.c 8

你想要这个getattr功能.

class search(object):
  def __init__(self):
    for key, value in test.items():
      if test[key]['active']:
        getattr(self, key)(test['key']['id'])
Run Code Online (Sandbox Code Playgroud)

根据评论,如果您不是100%肯定该方法将存在,您可以hasattr(self, name)提前执行检查,但它等同于:

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

  • 确保方法存在的最好方法是尝试`getattr`并捕获`AttributeError` - 这就是`hasattr`所做的! (2认同)