首页 > 解决方案 > 使用装饰器将函数添加到字典

问题描述

我想将函数添加到使用装饰器存储在对象中的字典中。我创建了一个类并添加了一个名为“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()

标签: pythonclassdictionaryargumentsdecorator

解决方案


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

推荐阅读