欢迎访问个人网络日志🌹🌹知行空间🌹🌹
1.通过函数定义装饰器
class MyObj:
def __init__(self, value):
self.value = value;
def set_value(self, value):
print("set value:",value)
self.value = value
def get_set_value_name(self):
print(self.set_value.__name__)
o = MyObj(10)
o.set_value(12)
o.get_set_value_name()
def log(f):
def w(*args, **kwargs):
print("begin to log")
return f(*args, **kwargs)
return w
class MyObj:
def __init__(self, value):
self.value = value;
@log
def set_value(self, value):
print(set_value.__name__)
print("set value:",value)
self.value = value
def get_set_value_name(self):
print(self.set_value.__name__)
o = MyObj(10)
o.set_value(120)
o.get_set_value_name()
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
class MyObj:
def __init__(self, value):
self.value = value;
@log("MyObj")
def set_value(self, value):
print("set value:",value)
self.value = value
def get_set_value_name(self):
print(self.set_value.__name__)
o = MyObj(10)
o.set_value(120)
o.get_set_value_name()
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
class MyObj:
def __init__(self, value):
self.value = value;
@log("MyObj")
def set_value(self, value):
print("set value:",value)
self.value = value
def get_set_value_name(self):
print(self.set_value.__name__)
o = MyObj(10)
o.set_value(120)
o.get_set_value_name()
输出
set value: 12
set_value
begin to log
set_value
set value: 120
w
MyObj set_value():
set value: 120
wrapper
MyObj set_value():
set value: 120
set_value
2.定义装饰器类
class logit(object):
def __init__(self, logfile='out.log'):
self.logfile = logfile
def __call__(self, func):
@functools.wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
with open(self.logfile, 'a') as opened_file:
opened_file.write(log_string + '\n')
self.notify()
return func(*args, **kwargs)
return wrapped_function
def notify(self):
pass
@logit()
def do_nothing():
pass
do_nothing()
输出
do_nothing was called
参考资料
欢迎访问个人网络日志🌹🌹知行空间🌹🌹
|