我想做到這一點:以編程方式確定函數的評估是否正在分配?
def foo():
if <a magical condition>:
return x
else:
poof()
# or...
def foo():
x = <a magical object>
return x
def poof():
print 'poof!'
bar = foo() # bar points to <a magical object> but poof() is not called
foo() # prints 'poof!'
我猜測它歸結爲circumstanses是什麼時,返回的對象的__del__
方法被調用。但也許有更好的辦法。就像函數本身知道它正在分配返回值一樣。我想我擔心依靠垃圾收集的時間。我也不喜歡那個全球at_end_of_program
的標誌。
我的解決辦法:
class Magic:
def __del__(s):
poof()
def foo():
x = Magic()
return x
def poof():
if not at_end_of_program:
print 'poof!'
bar = foo() # No poof.
foo() # prints 'poof!'
是的,我必須避免重新分配'bar'直到將'at_end_of_program'標誌設置爲True。我試圖有時傳遞,有時關閉一個由函數創建的COM對象,具體取決於它是否被請求或被函數的調用所請求。收集垃圾時,COM對象不會關閉。 – Paul 2009-11-13 03:54:57