Python:如何从类装饰器中访问装饰类的实例?

时间:2010-02-02 01:07:57

标签: python decorator

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

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()

我需要装饰实际的课程吗?

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分: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')

答案 2 :(得分:1)

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()