【发布时间】:2018-02-04 13:34:31
【问题描述】:
我读到我们可以在 python 中创建任何函数的引用,但我也读到在创建装饰器时我们使用称为“@”的特殊语法:例如:@decorator_function
而这个@decorator_function 等于new_function=decorator_function(new_function)
所以我的怀疑是在我看来:
anything = decorator_function(new_function)new_function=decorator_function(new_function)
两者都扮演着闭包的角色,但都导致不同的输出。那么两者有什么大的区别呢?
示例代码:
def deco(fn):
def wrapper(*args):
print('called')
return fn(*args)
return wrapper
def something(x):
if x == 0:
print('first')
something(x+1)
else:
print('hello')
print('new name')
a = deco(something)
a(0)
print('\nreassigning to the same name')
something = deco(something)
something(0)
【问题讨论】:
标签: python python-2.7 decorator python-decorators