定义
在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。
由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数。
本质上,decorator就是一个返回函数的高阶函数。
不带参的装饰器:
调用被装饰的函数时,会把自己作为参数传入装饰器方法并执行
def deco_test(n): # 参数n为被装饰的方法
def test(a, b):
return n(a, b)
return test
@deco_test # 相当于deco_method = deco_test(deco_method)
def deco_method(a, b):
return a + b
deco_method(1, 2)
输出:3
带参的装饰器:
def deco_test(n): # n为传入的参数
def funx(f): # f为被装饰的方法
def funy(a, b):
return f(a, b)
return funy
return funx
@deco_test('num')
def deco_method(a, b):
return a + b
deco_method(1, 2)
输出: 3
类装饰器:
class cached_property(object):
def __init__(self, func, name=None):
self.func = func # func为<function RawDb.columns at 0x10f904200>
self.__doc__ = getattr(func, '__doc__')
self.name = name or func.__name__
def __new__(cls, *args, **kwargs): # cls 为<class '__main__.cached_property'>
return super(cached_property, cls).__new__(cls)
def __get__(self, instance, cls=None):
if instance is None:
return self
res = instance.__dict__[self.name] = self.func(instance)
{"columns" : 1}
return res
import time
class RawDb(object):
@cached_property
def columns(self):
time.sleep(5)
return 1
# columns = cached_property()
rd = RawDb()