''' class Test(object): print("---------test---------") t = Test() t() # Traceback (most recent call last): # File "F:/python项目/09Day/03python高级/01类作为装饰器.py", line 6, in <module> # t() # TypeError: 'Test' object is not callable #如果t一个函数,可以直接使用t()来进行调用, #T是一个对象,怎么来调用对象呢? #没有重写call方法,不能直接调用,直接调用会初上上面的报错 ''' #重写了__call__方法,类的对象就能够被调用,直接使用t()来调用类,并打印__call__方法里面的内容 class Test(object): print("--------test1----------") def __call__(self, *args, **kwargs): print("---------test---------") #注意一点,__call__方法里面的是最后执行。 def eat(self): print("-----------eat-------------") print("---------test2---------") t = Test() t()
执行结果:D:\python3.6\pythonw.exe F:/python项目/09Day/03python高级/01类作为装饰器.py
--------test1----------
---------test2---------
---------test---------
Process finished with exit code 0
类做为装饰器:
class Test(object): def __init__(self,func): print("-------初始化-------") print("func name is %s" %func.__name__) self.__func = func #类的私有属性self.__func也指向了test1函数的内存地址。 def __call__(self, *args, **kwargs): #test1 = Test(test1) #调用类的对象。就会调用call方法。 print("------装饰器中的功能-------") self.__func() #self.__func指向了函数test1的内存地址。这句话相当于执行test1()函数。 #使用类作为装饰器,需要重写Call方法,没有调用test1()方法的时候,执行代码得到下面的结果 # -------初始化------- # func name is test1 @Test #相当于 test1 = Test(test1) 也相当于func指向了下面函数test1的名字, 前面的test1指向了 Test()这个对象。 # 调用test1对象的时候相当于调用类方法Test(),调用类方法必调用__call方法,调用call方法的时候,先执行 print("------装饰器中的功能-------") #然后在执行self.__func() ,因为self.__func函数指向的是test1函数,test1()相当于执行self.__func(). def test1(): print("----test1---------") test1() #调用test1
D:\python3.6\pythonw.exe F:/python项目/09Day/03python高级/02类作为装饰器.py
-------初始化-------
func name is test1
------装饰器中的功能-------
----test1---------
Process finished with exit code 0