我正在学习装饰设计模式教程 (归功于Ryoo Jungwoo)
我很好奇为什么我可以换行:return decorator
和print(hello_world())
与return decorator()
和print(hello_world)
from functools import wraps
def make_blink(function):
"""Defines the decorator"""
@wraps(function)
# Define the inner function
def decorator():
# Grab the return value of the function being decorated
ret = function()
# Add new functionality to the function being decorated
return "<blink>"+ ret + "<b/link>"
return decorator #return decorator()#<THIS LINE HERE SWAPPED
# Apply the decorator here!
@make_blink
def hello_world():
"""Original function! """
return "Hello, World!"
# Check the result of decorating
print(hello_world()) #print(hello_world) #<THIS LINE HERE SWAPPED
翻译不是每次都在做不同的事情吗?我只是想了解一些情况,以便更好地了解正在发生的事情
装饰器实际上就是函数,函数就是对象。你知道吗
台词
基本上与
但是函数对象从来没有首先分配给
hello_world
(它在堆栈上,以便传递给装饰器)。你知道吗所以无论你从
make_blink()
返回什么,都会被分配回hello_world
。它可以是函数对象,但也可以是完全不同的对象。你知道吗因此,当您使用
return decorator
时,您告诉Python将hello_world
设置为嵌套函数对象。当您使用return decorator()
时,您告诉Python使用decorator()
函数的结果。这里,这是一个字符串值。就好像你这么做了:对于这个特定的例子来说,这很好,因为
hello_world()
函数体每次只返回相同的字符串。你知道吗但是,如果您更改了原始的
hello_world()
函数体,每次调用时都返回不同的内容,会怎么样?如果你有:现在,从
make_blink()
调用返回的结果有很大的不同!对于模块的顶层,在导入时,装饰器只执行一次。如果您使用return decorator()
,那么只需运行random.choice()
一次,就可以将random_greeting
的值固定到一个静态字符串结果中。你知道吗一般来说,装饰程序需要再次返回一个可调用对象。可以是原始函数(decorator只是更新某种注册)、包装函数(在调用原始函数之前或之后执行额外的操作),甚至是完全不同的东西。但这不是一成不变的,翻译也不在乎。你知道吗
decorator只是可重用的东西,可以在程序中使用,这是一种工具。如果您对返回原始函数结果的装饰器有特定的用途,那么您可以自由地这样做。你知道吗
相关问题 更多 >
编程相关推荐