1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| class Tree(object):
def __init__(self, parent=None):
self._children = []
if parent is None:
self._root = self
self._parent = None
else:
self._root = parent._root
parent.insert(self)
@property
def is_root(self):
return self._parent is None
def insert(self, item):
assert item._root is self._root, ''
item._parent = self
self._children.append(item)
@staticmethod
def move(item, to):
assert not item.is_root, "can't detach root"
item._parent._children.remove(item)
to.insert(item)
class MyTree(Tree):
def __init__(self, ident, parent=None):
super(MyTree, self).__init__(parent)
self._ident = ident
def dumps(self):
s = '{ "id":%s ' % self._ident
if len(self._children):
s += 'children: [ %s ]' % ', '.join([item.dumps() for item in self._children ])
return s + '}'
CTree = MyTree
root = CTree(0)
n1 = CTree(1, parent=root)
n2 = CTree(2, parent=root)
n3 = CTree(3, parent=n2)
print root.dumps()
##---
CTree.move(n3, n1)
print root.dumps() |