即嵌套使用
def dec1(f):
def runit():
print('dec start')
f()
print('dec end')
return runit
@dec1
def func1():
print('in func1')
func1()
装饰器类
class mydec():
def __init__(self, fn):
print('构造')
self.fn = fn
def __call__(self):
print('执行')
self.fn()
@mydec
def fun():
print('func')
普通装饰器
def dec1(f):
def runit(*args, **kwargs):
print('dec start')
f(*args, **kwargs)
print('dec end')
return runit
装饰器类
def __call__(self, *argv, **kwargs):
print('执行')
self.fn(*argv, **kwargs)
类成员self 类似于一个argv,因此类成员也可直接使用带参装饰器
def dec1(f):
def runit(*args, **kwargs):
print('dec start')
f(*args, **kwargs)
print('dec end')
return runit
class test_dec:
def __init__(self):
pass
@dec1
def run(self):
print('888')
obj = test_dec()
obj.run()
def dec(f):
def inner(*args, **kwargs):
print('执行到inner')
return f(*args, **kwargs)
return inner
@dec
class demo:
def __init__(self):
print('执行self')
def __new__(cls):
print('执行new')
r = super().__new__(cls)
return r
obj = demo()
执行到inner
执行new
执行self