【问题标题】:I am getting "TypeError: decorator_factory() takes exactly 2 arguments (1 given)"我收到“TypeError:decorator_factory() 正好需要 2 个参数(给定 1 个)”
【发布时间】:2017-03-12 17:55:08
【问题描述】:

为什么我在此处运行调用时会出现上述异常。我觉得我错过了一些非常明显的东西..

def decorator_factory(arg1, arg2):
    def simple_decorator(f):
        def wrapper():
              print arg1
              f()
              print arg2
    return wrapper
return decorator_factory

@decorator_factory("what the heck", "what the heck2")
def hello():
print "Hello World"

hello()

【问题讨论】:

  • 请仔细检查您的缩进。除此之外,您所写的内容并没有明显的错误。请提供完整回溯的minimal reproducible example
  • 必须是return simple_decorator 而不是return decorator_factory
  • 对不起,让我在这里再次复制它。看起来在这里粘贴代码给了我你们在这里提到的问题。

标签: python python-2.7 python-decorators


【解决方案1】:

必须是return simple_decorator 而不是return decorator_factory

def decorator_factory(arg1, arg2):
    def simple_decorator(f):
        def wrapper():
              print arg1
              f()
              print arg2
        return wrapper
    return simple_decorator # <--- HERE 

@decorator_factory("what the heck", "what the heck2")
def hello():
    print "Hello World"

hello()

【讨论】:

    猜你喜欢
    • 2016-12-28
    • 1970-01-01
    • 2015-07-17
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多