双层装饰器输出星号、百分号:
1 #!usr/bin/env/python35 2 # -*- coding:utf-8 -*- 3 # author: Keekuun 4 5 import functools 6 7 8 def star(func): 9 @functools.wraps(func) 10 def wrappers(*args, **kwargs): 11 print('*'*50) 12 func(*args, **kwargs) 13 print('*'*50) 14 return wrappers 15 16 17 def percent(func): 18 @functools.wraps(func) 19 def wrappers(*args, **kwargs): 20 print('% '*10) 21 func(*args, **kwargs) 22 print('% '*10) 23 return func 24 return wrappers 25 26 27 @star 28 @percent 29 def hello(): 30 print(' hello') 31 32 33 hello()
能否写出一个@log的decorator,使它既支持:
@log
def f():
pass
又支持:
@log('execute')
def f():
pass
还支持:
@log()
def f():
pass
def log(msg=''): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): if isinstance(msg, (int, str)): print(msg) else: pass func(*args, **kwargs) return wrapper return decorator if isinstance(msg, (int, str)) else decorator(msg) @log(11) # int传入 def hello_world1(): print('Hello world') @log('hi_11') # str传入 def hello_world2(): print('Hello world') @log() # ()空 def hello_world3(): print('Hello world') @log #无 def hello_world4(): print('Hello world') hello_world1() hello_world2() hello_world3() hello_world4()