[英]Flow of python decorator functions
我試圖理解以下示例,我發現解釋decorators
:
#!/usr/bin/python
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
#return "1"
return func_wrapper
get_text = p_decorate(get_text)
print get_text("John")
這個輸出是:
<p>lorem ipsum, John dolor sit amet</p>
我決定嘗試更改此功能並注釋掉return func_wrapper
並將其替換為return "1"
。
當我這樣做時,我收到錯誤:
TypeError: 'str' object is not callable
我有兩個問題:
當行
print get_text("John")
執行,是
def func_wrapper(name):
用"John"
初始化? 運行此行后的事件順序是什么?
為什么我會收到此錯誤,因為最終,最終是不是最終返回的string
?
如果有人能用這段代碼解釋事件的流程,我將非常感激。
你在這里打電話給裝飾者:
get_text = p_decorate(get_text)
通常,裝飾器將函數替換為另一個可調用函數(例如,另一個函數),或返回原始函數但已注冊有關它的信息。
但是通過將p_decorate()
的返回值更改為"1"
而不是函數包裝器,你'打破了' get_text
因為它現在不再是一個函數。 你不能像調用字符串一樣調用字符串對象。
之前, p_decorate()
返回了func_wrapper()
函數對象,因此get_text
被反彈以指向該函數。 調用get_text('John')
確實調用了嵌套函數。 然后確實用'John'
作為參數調用func_wrapper()
,是的。 函數畢竟只是對象,您可以將這些對象分配給您喜歡的任何有效Python名稱。
當func_wrapper()
時,它又調用func()
,這是p_decorate()
的參數。 同樣,函數只是對象 ,因此調用了p_decorate(get_text)
, func
最終仍然綁定到原始的get_text
函數對象。 調用func()
調用原始函數。
您可以在Python Tutor中看到完整的調用流程。
只是為了補充。
當你想在decorator中傳遞args時,你使用嵌套函數:
def decorator(func):
def wrapper(*args, **kwargs):
print('My args:', *args, **kwargs)
return func(*args, **kwargs)
return wrapper
所以你裝飾:
def my_function(*args, **kwargs):
pass
my_function = decorator(my_function)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.