装饰实例方法
的时候容易出现莫名其妙的错误,所以一般加上get方法,来个案例:
import types
from functools import wraps
class Log(object):
def __init__(self, func):
wraps(func)(self) # @wraps(func) 访问不到,所以用这种方式
self.__func = func
def __call__(self, *args, **kvs):
print("%s log_info..." % self.__func.__name__)
return self.__func(*args, **kvs)
# 装饰实例方法的时候容易出现莫名其妙的错误,所以一般加上get方法
# eg:show() missing 1 required positional argument: 'self'
def __get__(self, instance, cls):
if instance is None:
return self
else:
return types.MethodType(self, instance)
class LoginComponent(object):
def __init__(self, name):
self.__name = name
@Log
def show(self):
"""实例方法"""
print("欢迎你:%s" % self.__name)
@classmethod
@Log # 写在下面("从下往上装,从上往下拆")
def login_in(cls):
"""类方法"""
print("登录ing")
@staticmethod
@Log
def show_news():
"""静态方法"""
print("今天的新闻是...")
def main():
LoginComponent.login_in()
LoginComponent.show_news()
login = LoginComponent("小明")
login.show()
if __name__ == '__main__':
main()
注意:本文归作者所有,未经作者允许,不得转载