我正在尝试了解脚本中使用修饰符的两个版本背后的逻辑。在脚本之一中,装饰器会自动调用,甚至不会被调用。
脚本1:
def outer_decorator(input_function):
def decorator(*args,**kwargs):
print "Outer Decorator Called"
output = input_function(*args,**kwargs)
return output
return decorator
class X:
@outer_decorator
def inner_decorator(input_function):
def decorator(*args,**kwargs):
output = input_function(*args,**kwargs)
print "Inner Decorator Called"
return output
return decorator
def z(self,a,b):
"""
Function returns a - b
"""
return a - b
x = X()
print(x.z(1,2))
输出
-1
因此,每当我运行脚本1时,我都会创建一个class X
对象,然后调用函数z
。因此,在这种情况下,内部装饰器函数不会在任何地方使用,因此不会被调用。
脚本2:
def outer_decorator(input_function):
def decorator(*args,**kwargs)
print "Inner Decorator Called"
return output
return decorator
@inner_decorator
def s(self,b):
"""
Function return a + b
"""
return a + b
def z(self,2))
因此,现在在上面的脚本中,我介绍了另一个使用function s
的{{1}}。但是我仍然只调用@inner_decorator
中的function z
。但是,当我运行此脚本时,会得到以下输出。
被称为外部装饰器
-1
那么为什么class x
被调用并正在打印?
是因为在某个地方使用的装饰器是由解释器处理的吗?