简体   繁体   中英

Understanding python decorator. why does this not work?

I am new to python and am fiddling with things. I really do not understand why this code does not work. Can you please help me understand what is happening here ?

from functools import wraps

class A:
    def __init__(self):
        self.methodName = 'temp1'
    def temp(self, i):
        print(self.__class__.__name__)
        print("hi" + str(i))
    def temp2(self):
        print("hey hey hey")

class B:
     pass

class C:
    def __call__(self, Func):
        @wraps(Func)
        def newFunc(*args, **kwargs):
            return Func(*args, **kwargs)
        return newFunc

if __name__ == '__main__':
    a = A()        
    setattr(B, a.methodName, a.temp)
    setattr(B, 'temp1', C().__call__(a.temp))
    b = B()    
    b.temp1(5)

Try this:

from functools import wraps
class A :
    def __init__(self):
        self.methodName = 'temp1'
    def temp(self, i) : 
        print (self.__class__.__name__)   
        print("hi" +str(i))  
    def temp2(self):
        print "hey hey hey"

class B :
     pass

class C :
    def __call__(self,Func) :
        @wraps(Func)
        def newFunc(self, *args, **kwargs) :
            return Func(*args, **kwargs);
        return newFunc


if __name__ == '__main__' :
    a = A()        
    setattr(B, a.methodName, a.temp)
    setattr(B, 'temp1', C().__call__(a.temp))
    b = B()    
    b.temp1(5)

Note that newFunc now takes self as its first argument.

The reason this works is that bound instance methods, like b.temp1 , always receive their bound instance as the first argument (in this case b ). Originally, you were passing all arguments via *args to a.temp . This meant that temp was being invoked with the arguments (a, b, 1) . Adding self to newFunc 's parameter list ensures that a is not mistakenly passed to temp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM