1、类装饰器
装饰器函数其实是这样一个接口约束,它必须接受一个callable对象作为参数,然后返回一个callable对象。在python中一般callable对象都是函数,但也有例外。只要某个对象重写了__call__()方法,那么这个对象就是callable的。
__call__()方法:一个对象是否可调用,看其中是否实现了__call__方法。
class Test(object):
def __call__(selfself):
print("---test---")
t = Test()
t()
运行结果:---test---
class Test(object):
def __init__(self,func):
print("初始化中",func.__name__)
self.func = func
def __call__(self):
print("---test---")
self.func()
def print1(self):
print("我是一个打印方法。")
#相当于 test = Test(test)
@Test
def test():
print("这是一个被装饰函数。")
test()
test.print1()
运行结果:
初始化中 test
---test---
这是一个被装饰函数。
我是一个打印方法。
2、元类