使用装饰器向字典添加函数
Add a function to a dictionary using a decorator
我想使用装饰器向存储在对象中的字典添加函数。
我做了一个 class 并添加了一个名为 'add' 的函数。该函数需要一个键和一个函数。
我希望当我调用 '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()
如果您可以使用 key
作为实际的函数名称,那么您实际上并不需要两个参数,那么您可以使用 .__name__
来获取函数的名称是 self.functions
字典中的 key
而 value
将是函数本身。
您可以使用以下内容:
class App:
def __init__(self):
self.functions = {}
def add(self, func):
self.functions[func.__name__] = func
app = App()
@app.add
def bye():
print('Goodbye')
>>> app.functions
# {'bye': <function __main__.bye()>}
>>> app.functions['bye']()
# Goodbye
找到答案:
我需要在里面添加另一个装饰器:
def add(self, key):
def adder(func):
self.functions[key] = func
return func
return adder
但正如另一位用户所说:
我可以使用“_name_”访问函数名称并将其用作键。
我想使用装饰器向存储在对象中的字典添加函数。 我做了一个 class 并添加了一个名为 'add' 的函数。该函数需要一个键和一个函数。 我希望当我调用 '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()
如果您可以使用 key
作为实际的函数名称,那么您实际上并不需要两个参数,那么您可以使用 .__name__
来获取函数的名称是 self.functions
字典中的 key
而 value
将是函数本身。
您可以使用以下内容:
class App:
def __init__(self):
self.functions = {}
def add(self, func):
self.functions[func.__name__] = func
app = App()
@app.add
def bye():
print('Goodbye')
>>> app.functions
# {'bye': <function __main__.bye()>}
>>> app.functions['bye']()
# Goodbye
找到答案: 我需要在里面添加另一个装饰器:
def add(self, key):
def adder(func):
self.functions[key] = func
return func
return adder
但正如另一位用户所说: 我可以使用“_name_”访问函数名称并将其用作键。