【发布时间】:2018-02-28 16:21:17
【问题描述】:
我正在编写一些代码,并且我有一个字典,其中键是任何字符串,值是函数。然后我遍历字典中的每个键并调用函数,如下所示:
class SomeClass:
dictionary = {}
# Not sure how to use this decorator function
def decorator(key):
def wrapper(funct):
self.dictionary[key] = funct
return funct
return wrapper
@decorator("some_val1")
def function_1(self):
...
@decorator("some_val2")
def function_2(self):
...
@decorator("some_val3")
def function_3(self):
...
def execute_all_functions(self):
for key, _ in self.dictionary.items():
self.dictionary[key]()
if __name__ == "__main__":
sclass = SomeClass()
sclass.execute_all_functions()
所以这应该填充dictionary:
{
"some_val1": function_1(),
"some_val2": function_2(),
"some_val3": function_3()
}
我收到了这个错误
self.dictionary[key] = funct
NameError: name 'self' is not defined
我怎么能做到这一点。帮助表示赞赏。
【问题讨论】:
-
您是否尝试将
self,添加到类中decorator和wrapper的定义中?def decorator(self,key):,def wrapper(self,funct):
标签: python python-3.x