我只是想知道我的理解https://docs.python.org/2/extending/extending.html#reference-counts權:循環引用和垃圾回收在Python
我有一個(出於某些目的必須有相互參考)兩大類:
class Foo(object):
def __init__(self, child):
self._child = child
self._child.parent = self
@property
def child(self)
return self._child
@child.setter
def child(self, value):
#Optional to delete reference to parent
'''
self._child.parent = None
'''
self._child = value
self._child.parent = self
class Child(object):
@property
def parent(self):
return self._parent
@parent.setter
def parent(self, value)
self._parent = value
在設置新的孩子之前,我是否需要製作self._child.parent = None
,以便老孩子可以被垃圾清理?我被上面的鏈接引用嚇倒了,這種情況是我不確定的。直到現在我發現的所有東西都描述了兩個元素被刪除並且有一個指向對方的情況。
請注意,這裏使用'property'是完全多餘的,不需要。只需使用'self.child'和'self.parent屬性即可。這當然不是Java中使用getter和setter的地方,如果需要的話,您可以隨時切換到使用屬性(例如,在設置或獲取時需要執行額外的處理)。 –
我知道,實際上在嘗試設置時有很多'setter'邏輯 - 我只是跳過所有這些以獲得更清晰的示例。 – MSeifert
雖然在這裏的'child.setter'屬性中可能會添加'self._child.parent = self'。 –