【发布时间】:2016-09-27 08:49:55
【问题描述】:
我正在尝试理解类似于以下内容的类方法定义:
@package(type='accounts', source='system')
def get(self, [other arguments]):
[function body]
@package 装饰器的含义是什么?我找不到这方面的文档。
【问题讨论】:
标签: python decorator python-decorators
我正在尝试理解类似于以下内容的类方法定义:
@package(type='accounts', source='system')
def get(self, [other arguments]):
[function body]
@package 装饰器的含义是什么?我找不到这方面的文档。
【问题讨论】:
标签: python decorator python-decorators
Python 标准库中没有默认的 package 装饰器。
装饰器只是一个简单的表达式;在同一个模块中将有一个package() 可调用(在那里定义为函数或类,或者从另一个模块导入)。
@package(type='accounts', source='system') 行执行表达式package(type='accounts', source='system'),其返回值用于修饰get() 函数。您可以将其解读为:
def get(self, [other arguments]):
[function body]
get = package(type='accounts', source='system')(get)
除了名称 get 只设置一次。
例如,package 可以定义为:
def package(type='foo', source='bar'):
def decorator(func):
def wrapper(*args, **kwargs):
# do something with type and source
return func(*args, **kwargs)
return wrapper
return decorator
所以package() 返回decorator(),而后者又返回wrapper(); package() 是一个装饰器工厂,生产实际的装饰器。
【讨论】: