在python中,我知道函式在呼叫它們的背景關系中運行,而不是在定義它們的背景關系中運行。但是,在下面的代碼中,函式從另一個函式回傳,它仍然可以訪問變數(特別是它定義的函式的串列“快取”),即使該函式現在超出范圍(我認為),所以我會盡管它的變數會被洗掉。但它也可以從當前背景關系訪問全域變數?
def wrapper(func):
cache = []
def func_new(n):
cache.append(func(n))
print(cache)
return func_new
def add1(n):
return(n 1)
x = wrapper(add1)
x(5)
x(2)
print(cache)
uj5u.com熱心網友回復:
不是嗎?
>>> x = wrapper(add1)
>>> x(5)
[6]
>>> x(2)
[6, 3]
>>> print(cache)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print(cache)
NameError: name 'cache' is not defined
至于在包裝器中定義的快取變數,它與其他地方的行為相匹配;該函式可以訪問定義它的所有變數。反之則不然;除非明確是全域變數,否則函式中定義的變數在背景關系范圍內不可訪問。
這個例子有幫助嗎?
>>> x = 4
>>> def test():
print(x)
>>> test()
4
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/391233.html
