如何在下面的代码中从字典中调用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)
你想要这个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)
| 归档时间: |
|
| 查看次数: |
2091 次 |
| 最近记录: |