2010-02-02 113 views
6

這裏是我的意思的例子: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

回答

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

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

+0

舊的答案解決新問題時,我喜歡它!感謝這個珍聞! – 2015-06-07 06:17:43

2

請在這種情況下,使用「自我」只是一個慣例注意到,一個方法只使用第一個參數作爲參考實例對象:

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

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

自我的說法是作爲第一個參數傳遞。您的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