【发布时间】:2021-01-05 06:08:57
【问题描述】:
我想将函数添加到使用装饰器存储在对象中的字典中。 我创建了一个类并添加了一个名为“add”的函数。该函数需要一个键和一个函数。 我希望当我调用“添加”函数时,我在下面定义的函数将使用装饰器中的给定键添加到我的字典中。
我只需将它添加到列表中就可以使用它,但我想用一个键来访问这些功能。
这是我的代码:
class App:
def __init__(self):
self.functions = {}
def add(self, key, func):
self.functions[key] = func
app = App()
@app.add("hello")
def print_hello():
print("hello")
这是错误:
@app.function("hello")
TypeError: function() missing 1 required positional argument: 'func'
这里是带有列表的工作代码:
class App:
def __init__(self):
self.functions = []
def add(self, func):
self.functions.append(func)
def loop_functions(self):
for f in self.functions:
f()
app = App()
@app.add
def print_hello():
print("hello")
app.loop_functions()
【问题讨论】:
-
你得到的错误是因为
def add(self, key, func):在使用列表中比你的add多了一个参数,但是你只将参数传递给key而不是func。跨度> -
我知道我为什么会收到这个错误。通常,在装饰器下定义的函数作为第一个参数传入,就像在我的列表示例中一样。但在这里我想传入一个额外的参数(键)和函数。
标签: python class dictionary arguments decorator