【问题标题】:getting arguments of the decorated function in python在python中获取装饰函数的参数
【发布时间】:2013-06-03 02:21:56
【问题描述】:

Python 装饰器中的包装器如何到达被装饰的函数参数? 例如:

def decorate(f):
    def wrapped_function(*args):
        print args
        f()
    return wrapped_function

@decorate
def my_function(*args):
    print("Hello world")

my_function("a")


# output
('a',)
Hello world

所以,我知道 Wrapped_function 是一个闭包, 因为它保留对 my_function 作为来自上层范围的变量的访问。 但它怎么可能带来理论上的论据呢?

【问题讨论】:

  • 我不明白你在问什么。你能改写一下这个问题吗?
  • 闭包是它获取f的方式,但与参数无关。它以与任何其他函数相同的方式获取它们——你调用它,你调用它的 args 作为它的参数传递。问题是原始函数f 如何获取参数。在你的例子中,它_doesn't_——如果你想要它,你必须调用f(*args)。 (在您的情况下,因为它需要 *args 并且从不访问它们,所以您可以侥幸逃脱。)
  • 谢谢,但我在下面寻找答案

标签: python arguments closures decorator


【解决方案1】:

这个:

@decorate
def my_function(*args):
    pass

本质上和这个是一样的:

my_function = decorate(my_function)

因此,wrapped_function 替换了my_function

这意味着:

my_function("a")

其实是这样的:

wrapped_function("a")

所以你已经将论据提交给wrapped_function。 您可以查看属性__name__

>>> my_function.__name__
'wrapped_function'

没有装饰 __name__ 将是 my_function.

【讨论】:

  • 这正是我要找的
    my_function("a") 将被wrapped_function("a")
    另外,my_function 和wrapped_function 必须具有相同的签名跨度>
猜你喜欢
  • 2018-01-21
  • 2010-11-03
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-27
相关资源
最近更新 更多