[英]Variable not being assigned value when returned from subprogram? Python 3?
[英]Why is there no error when the returned function is not being assigned?
我正在學習Python(使用Python 3.6.8)中的一流函數的概念,無法弄清楚為什么下面的代碼沒有顯示任何錯誤。
def outer_fn(msg):
def inner_fn():
print(msg)
return inner_fn
outer_fn("text")
因為這是一件非常好的事情。
有時,您因其副作用而調用函數(它打印某些內容,將某些內容保存到數據庫中,更改某些變量),並且對返回值不感興趣。 Python不會告訴您對返回值做任何事情,它只是為您調用該函數。
它沒有顯示錯誤,因為您的代碼沒有任何錯誤,您需要像這樣調用內部函數:
outer = outer_fn("text")
outer() # call inner_fn
完整代碼:
def outer_fn(msg): #outer function
def inner_fn(): #inner function
print(msg) #able to acces the variable of outer function
return inner_fn
outer = outer_fn("text")
outer() # call inner_fn
輸出:
text
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.