python - 使用装饰器将函数添加到字典
问题描述
我想将函数添加到使用装饰器存储在对象中的字典中。我创建了一个类并添加了一个名为“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__
来获取函数的名称,该名称将key
在您的self.functions
字典中,而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
推荐阅读
- python - 我缺少什么来修复与金融 API 相关的 SSL 错误?
- reactjs - 什么时候在 React 中被归类为“未定义”?
- swift - 从视图控制器对 tableview 控制器进行 segue
- c# - Un / Load ViewComponent Content in Modal OnClick
- javascript - Reactjs - 在按钮单击时重新呈现数据
- r - 不同数据集的相同计算
- vim - 在 vim 中注释几行不起作用
- firebase - Flutter Firestore 消息通知
- c++ - 如何通过显式初始化解决这个继承问题?
- javascript - 在反应和打字稿中存储登录令牌