【问题标题】:Python: How do I access an decorated class's instance from inside a class decorator?Python:如何从类装饰器内部访问装饰类的实例?
【发布时间】:2010-02-02 01:07:56
【问题描述】:

这是我的意思的一个例子:

class MyDecorator(object):    
    def __call__(self, func):
        # At which point would I be able to access the decorated method's parent class's instance?
        # In the below example, I would want to access from here: myinstance
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper

class SomeClass(object):
    ##self.name = 'John' #error here
    name="John"

    @MyDecorator()
    def nameprinter(self):
        print(self.name)

myinstance = SomeClass()
myinstance.nameprinter()

我需要装饰实际的班级吗?

【问题讨论】:

  • self.name='John'... 那是什么?

标签: python decorator


【解决方案1】:
class MyDecorator(object):
    def __call__(self, func):
      def wrapper(that, *args, **kwargs):
        ## you can access the "self" of func here through the "that" parameter
        ## and hence do whatever you want        
        return func(that, *args, **kwargs)
      return wrapper

【讨论】:

  • 我喜欢旧答案解决新问题!感谢这个花絮!
【解决方案2】:

请注意,在此上下文中使用“self”只是一种约定,方法只是使用第一个参数作为对实例对象的引用:

class Example:
  def __init__(foo, a):
    foo.a = a
  def method(bar, b):
    print bar.a, b

e = Example('hello')
e.method('world')

【讨论】:

    【解决方案3】:

    self 参数作为第一个参数传递。您的 MyDecorator 也是一个模拟函数的类。更容易使其成为实际功能。

    def MyDecorator(method):
        def wrapper(self, *args, **kwargs):
            print 'Self is', self
            return method(self, *args, **kwargs)
        return wrapper
    
    class SomeClass(object):
        @MyDecorator
        def f(self):
           return 42
    
    print SomeClass().f()
    

    【讨论】:

    • 感谢您的回答,但这不是我要问的。我正在寻找从类装饰器内部访问类实例。检查 jldupont 的答案。
    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 2019-02-03
    • 1970-01-01
    相关资源
    最近更新 更多