2010-02-02 12 views
6

Oto przykład tego, co mam na myśli:Python: Jak uzyskać dostęp do instancji udekorowanej klasy z wnętrza dekoratora klasy?

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

Czy muszę ozdobić aktualną klasę?

+0

'self.name = 'John'' ... co to jest? – jldupont

Odpowiedz

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

Naprawdę, dzięki za tę odrobinę informacji! – orokusaki

+0

Uwielbiam, gdy stare odpowiedzi rozwiązują nowe problemy! Dzięki za ten smakołyk! –

2

Proszę zauważyć w tym kontekście, że korzystanie z „ja” jest tylko konwencja, metoda po prostu używa pierwszego argumentu jako odniesienie do obiektu instancji:

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

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

Samo argument jest przekazany jako pierwszy argument. Również twoja MyDecorator jest klasą emulującą funkcję. Łatwiej, aby była to faktyczna funkcja.

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

Dzięki za odpowiedź, ale nie o to pytałem. Szukam dostępu do instancji klasy od wewnątrz dekoratora klasy. Sprawdź odpowiedź jlduponta. – orokusaki

Powiązane problemy