【问题标题】:In Python, how can I get the name of the function passed to my decorator with parameters?在 Python 中,如何获取带参数传递给装饰器的函数名称?
【发布时间】:2019-11-20 12:52:55
【问题描述】:

我正在尝试创建一个装饰器,它将验证参数是否存在并检索被装饰的方法的名称。

我能够在函数的第二层访问方法的名称,但不能访问第一层。

比如我有这个装饰器

def p_decorate(name, *a, **k):
    print(name + ' is at object: ')
    print a #I would like to get the method object here
    def fn(*a, **k)
        print a #object prints here instead
    return fn
return p_decorate

我想装饰这门课

class Person(object):
    @p_decorate('John')
    def get_fullnameobject(self):
        return self.name

我希望它打印出来:

John is at object: (<function get_fullnameobject at 0x000000003745A588>,)
(<function get_fullnameobject at 0x000000003745A588>,)

但输出是:

John is at object: ()
(<function get_fullnameobject at 0x000000003745A588>,)

【问题讨论】:

    标签: python methods decorator python-decorators


    【解决方案1】:

    函数p_decorate调用,只有参数John*a**k 都是空的),因此你得到一个a 的空元组.

    请注意,返回的 fn 可调用对象随后会与 get_fullnameobject 可调用对象一起调用。

    更重要的是,您当前的实现是不完整的,因为您永远无法调用该方法——您需要另一个闭包才能真正做到这一点。

    【讨论】:

      【解决方案2】:

      您需要另一个嵌套函数来定义一个接受参数的装饰器。

      def p_decorate(name):
          def _(f):
              print(name + ' is at object: ')
              print f
              def fn(*a, **k):
                  # Do something, but ultimately you probably want to call f
                  ...
              return fn
          return _
      

      p_decorate("John") 返回实际的装饰器,它将get_fullnameobject 作为其f 参数并返回新的fn 对象以绑定到get_fullnameobject。没有装饰器语法,用法看起来像

      def get_fullnameobject(self):
          return self.name
      
      get_fullnameobject = p_decorate("John")(get_fullnameobject)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-01
        • 1970-01-01
        • 2012-08-22
        • 1970-01-01
        • 2016-02-14
        • 2021-11-21
        • 1970-01-01
        • 2020-12-18
        相关资源
        最近更新 更多