decorator
# 装饰器
# 简单使用
from functools import wraps
def a_new_decorator(func):
@wraps(func)
def wrapTheFunction():
print('some action before func')
func()
print('some action after func')
return wrapTheFunction
## @a_new_decorator
def func():
print('func run')
## output wrapTheFunction
print(func.__name__)
if __name__ == '__main__':
nFunc = a_new_decorator(func)
nFunc()
## func()
等价于下面
from functools import wraps
def a_new_decorator(func):
@wraps(func)
def wrapTheFunction():
print('some action before func')
func()
print('some action after func')
return wrapTheFunction
@a_new_decorator
def func():
print('func run')
## output wrapTheFunction
print(func.__name__)
if __name__ == '__main__':
## nFunc = a_new_decorator(func)
## nFunc()
func()
- 装饰器可以看作返回函数的函数
a_new_decorator
, 返回内部创建函数wrapTheFunction
func.__name__
,输出的内部创建的函数名,一般可以加上@wraps(func)
, 变成函数func
# 当函数有参数
def singleton(cls):
instance = {}
def _singleton(*args, **kwargs):
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return _singleton
- 这是一个单例模式的写法