[英]Python: defining a function inside another function
我有一個 function,我在另一個 function 中定義了它。
def foo():
x = something
def bar(list=[]):
list.append(x)
return x
return bar
我有兩個問題:
foo
返回bar
時, bar
如何保持對x
的訪問? 此時, x
僅在foo
內部已知,但是當我們退出foo
時, bar
如何知道x
是什么?bar
有一個可變的默認參數。 當返回的 function bar
超出 scope 時,這個參數list
是否從 memory 中刪除? 每次我調用bar
時它都會越來越大,我想確保它在不再使用時被刪除。 bar
通過創建閉包來保持對x
的訪問:
>>> def foo():
... x = 42
... def bar(list=[]):
... list.append(x)
... return x
... return bar
...
>>> func = foo()
>>> func
<function foo.<locals>.bar at 0x7fcae19ac050>
>>> func.__closure__
(<cell at 0x7fcae1b19910: int object at 0x1080d99a0>,)
至於默認參數,你問“當返回的 function bar
超出 scope 時,這個參數list
是否從 memory 中刪除?”。
函數是對象。 對象不是scope中的go,scope是變量的屬性。 如果您的 function object 不再被引用,那么與任何其他 object 一樣,它可用於垃圾回收。 在 CPython 中,這是在引用計數達到零之后立即發生的。 function arguments 的默認值只是存儲為一個屬性,就像任何其他 object 一樣:
>>> func.__defaults__
([],)
>>>
所以是的,所有這些都將像往常一樣清理干凈。 如果 function object 是唯一引用它的 object,那么當 function object 不復存在時,列表的引用計數變為零,然后它可用於垃圾回收。
您可以通過定義一個冗長的終結器並將其用作默認值來向自己展示這一點:
>>> class Bar:
... def __del__(self):
... print('goodbye from ', self)
...
>>> def foo():
... def bar(x=Bar()):
... x.baz = 42
... return bar
...
>>> func = foo()
>>> func = foo()
goodbye from <__main__.Bar object at 0x7fcae1b19950>
>>> func = foo()
goodbye from <__main__.Bar object at 0x7fcae1b19910>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.