【问题标题】:Add a function to a dictionary using a decorator使用装饰器将函数添加到字典
【发布时间】: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


【解决方案1】:

找到答案: 我需要在里面添加另一个装饰器:

def add(self, key):
    def adder(func):
        self.functions[key] = func
        return func
    return adder

但正如另一位用户所说: 我可以使用 '_name_' 访问函数名称并将其用作键。

【讨论】:

    【解决方案2】:

    如果您可以将key 作为实际的函数名,那么您实际上并不需要两个参数,那么您可以使用.__name__ 来获取函数的名称,即key in您的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      • 2017-01-09
      • 2019-05-16
      • 2019-03-12
      • 2016-03-08
      • 1970-01-01
      • 2013-07-29
      相关资源
      最近更新 更多