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

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

问题描述:

这里是我的意思的例子:Python:如何从类装饰器中访问装饰类的实例?

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

我需要装饰实际的类?

+0

'self.name ='John'' ...那是什么? – jldupont 2010-02-02 01:22:16

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 
+0

真的,谢谢你的信息! – orokusaki 2010-02-02 01:22:41

+0

旧的答案解决新问题时,我喜欢它!感谢这个珍闻! – 2015-06-07 06:17:43

请在这种情况下,使用“自我”只是一个惯例注意到,一个方法只使用第一个参数作为参考实例对象:

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

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

自我的说法是作为第一个参数传递。您的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() 
+0

谢谢你的回答,但那不是我问的问题。我期待从类装饰器中访问类实例。检查jldupont的答案。 – orokusaki 2010-02-02 18:16:01