>>> import functools
>>> def log(txt):
... if isinstance(txt,str):
... def log1(func):
... @functools.wraps(func)
... def wraps(*a,**kw):
... print('begin call:%s'%txt)
... func(*a,**kw)
... print('end call:%s'%txt)
... return wraps
... return log1
... else:
... @functools.wraps(txt)
... print('begin call')
... txt(*a,**kw)
... print('end call')
...
>>> @log('带参数的装饰器')
... def now(x,y):
... print(x*y)
>>> now(2,3)
begin call:带参数的装饰器
6
end call:带参数的装饰器
>>> @log
... def add(x,y):
... print(x+y)
>>> add(2,3)
begin call
5
end call
Sign in to make a reply
真诚的刘海柱
>>> import functools
>>> def log(txt):
... if isinstance(txt,str):
... def log1(func):
... @functools.wraps(func)
... def wraps(*a,**kw):
... print('begin call:%s'%txt)
... func(*a,**kw)
... print('end call:%s'%txt)
... return wraps
... return log1
... else:
... @functools.wraps(txt)
... def wraps(*a,**kw):
... print('begin call')
... txt(*a,**kw)
... print('end call')
... return wraps
...
>>> @log('带参数的装饰器')
... def now(x,y):
... print(x*y)
...
>>> now(2,3)
begin call:带参数的装饰器
6
end call:带参数的装饰器
>>> @log
... def add(x,y):
... print(x+y)
...
>>> add(2,3)
begin call
5
end call