我对Python相对来说是[[new,并且我正与装饰器混为一谈,但我发现自己一直沉迷于如何解释运行装饰函数后得到的输出。这是代码:
我首先定义了这样的函数添加
def add(a, b):
'''Returns the sum of two numbers a and b'''
return a + b
然后我像这样创建了一个装饰器
def decorator_function(somefunction):
def wrapper_function(*args, **kwargs):
return f'{somefunction(*args, **kwargs)}!!!'
return wrapper_function
@decorator_function
def add(a, b):
'''Returns the sum of two numbers a and b and since it is decorated it is going to return the
result with 3 !!!'''
return a + b
然后我像这样运行函数add并得到以下输出
>>> add(5, 15)
'20!!!'
然后我像这样运行函数并获得了不同的输出
>>> result = decorator_function(add)
>>> result(5, 15)
'20!!!!!!' # Why did I get 6 '!'
>>> add = decorator_function(add)
>>> add(5, 15)
'20!!!!!!' # Why did I get 6 '!'?
现在我不明白为什么我得到6个感叹号
@decorator_function
[如果以后写,请写
decorator_function(add),
实际上是:
decorator_function(decorator_function(add)).