开发者

Python: How do I access an decorated class's instance from inside a class decorator?

Here's an example of what I mean:

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

Do I need to decorate the actual class?


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


Please notice in this context that the use of "self" is just a convention, a method just uses the first argument as a reference to the instance object:

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

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


The self argument is passed as the first argument. Also your MyDecorator is a class emulating a function. Easier to make it an actual function.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜