我寫了一個類,如下所示。我想將'父項'的屬性添加到我的基類節點。我想知道如果有人能告訴我如何正確地做到這一點。我已經得到了如何做到這一點的指導,但我並不完全確定如何寫出語法。這是建議的方式來做到這一點...python父母子女關係課
通常我會隱藏如此 其集時,前面的家長的孩子陣列可以被修改,從而 如果你說N A特性背後的父屬性。父= X,它實際上移除節點n從它的父 和設置父值
class Node(object):
def __init__(self, name, attributes, children):
self.name = name
self.attributes = attributes if attributes is not None else {}
self.children = children if children is not None else []
class Camera(Node):
def __init__(self, name="", attributes=None, children=None, enabled=True):
super(Camera, self).__init__(name=name, attributes=attributes, children=children)
self.enabled = enabled
更新
import weakref
class Node(object):
_parent = None
def __init__(self, name, attributes, children, parent):
self.name = name
self.attributes = attributes if attributes is not None else {}
self.children = children if children is not None else []
self.parent = parent
for child in children:
child.parent = self
@property
def parent(self):
return self._parent() if self._parent is not None else None
@parent.setter
def parent(self, newparent):
oldparent = self.parent
if newparent is oldparent:
return
if oldparent is not None:
oldparent.children.remove(self)
if self not in newparent.children:
newparent.children.append(self)
self._parent = weakref.ref(newparent) if newparent is not None else None
class Camera(Node):
def __init__(self, name="", attributes=None, children=None, enabled=True, parent=None):
super(Camera, self).__init__(name=name, attributes=attributes, children=children, parent=parent)
self.enabled = enabled
Camera()
附加說明:最好使用'weakref.ref'或'weakref.proxy'來存儲'_parent'屬性(我們假設'parent'是一個'property',所以在這種情況下慣例通常是用下劃線前綴命名「真實」屬性)。否則,你的樹,保證創建參考週期,因此他們不會被確定性清理(如果有的螺母禁用循環GC,或者在週期的任何對象都有一個'__del__'終結了'class'內存泄漏, [在Python 3.3及更早版本中,cyclic gc無法處理它](https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-442))。 – ShadowRanger
什麼即時通訊希望做父母的相機到另一臺相機 – JokerMartini