目标:
弄清楚类装饰器的原理与实现
1 代码
class StudWithParams:
def __init__(self, name, age):
self.name = name
self.age = age
def __call__(self, func):
print "enter __call__"
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result
return wrapper
@StudWithParams("chao", 31)
def my_add(a, b):
return a + b
class StudWithoutParams:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print "enter __call__"
result = self.func(*args, **kwargs)
return result
@StudWithoutParams
def my_add2(a, b):
return a + b
def process():
result = my_add(1, 1)
print result
result = my_add2(3, 3)
print result
if __name__ == "__main__":
process()
2 总结
2.1类装饰器的__init__函数会被执行且只执行一次。
2.2无参类装饰器的func从__init__中传入,被装饰的参数从__call__中传入
2.3有参类装饰器的参数从__init__中传入,func从__call__中传入,
被装饰的参数从__call__中定义的wrapper方法接收并处理
参考:
https://blog.csdn.net/itlanyue/article/details/82147720