def warp(callback):
def f(*args, **kwargs):
print('調用之前')
callback(*args, **kwargs)
print('調用之後')
return f
@warp
def hello(name: str = '未設置'):
print(f'hello {
name}')
if __name__ == '__main__':
hello('yimt')
Output
調用之前
hello yimt
調用之後
def warp(name: str):
def f1(callback):
def f2(*args, **kwargs):
kwargs['name'] = name
print('調用之前')
callback(*args, **kwargs)
print('調用之後')
return f2
return f1
@warp('yimt')
def hello(name: str = '未設置'):
print(f'hello {
name}')
if __name__ == '__main__':
hello()
Output
調用之前
hello yimt
調用之後
def wrap(callback):
def f(*args, **kwargs):
print('調用之前')
r = callback(*args, **kwargs)
print('調用之後')
return r
return f
class A:
@wrap
def hello(self, name: str = '未設置'):
print(f'hello {
name}')
a = A()
a.hello('yimt')
Output
調用之前
hello yimt
調用之後
def wrap(name: str):
def f1(callback):
def f2(*args, **kwargs):
kwargs['name'] = name
print('調用之前')
r = callback(*args, **kwargs)
print('調用之後')
return r
return f2
return f1
class A:
@wrap('yimt')
def hello(self, name: str = '未設置'):
print(f'hello {
name}')
a = A()
a.hello()
Output
調用之前
hello yimt
調用之後
def warp_a(callback):
def f(*args, **kwargs):
print('a調用之前')
callback(*args, **kwargs)
print('a調用之後')
return f
def warp_b(callback):
def f(*args, **kwargs):
print('b調用之前')
callback(*args, **kwargs)
print('b調用之後')
return f
@warp_a
@warp_b
def hello(name: str = '未設置'):
print(f'hello {
name}')
if __name__ == '__main__':
hello('yimt')
Output
a調用之前
b調用之前
hello yimt
b調用之後
a調用之後