有一个关于二叉树类的例子。
首先我定义类树。
>>> class Tree(object):
>>> def __init__(self, data=None, left=None, right=None):
>>> self.data = data
>>> self.left = left
>>> self.right = right
>>> def inorder(self):
>>> if self.left:
>>> for x in self.left.inorder():
>>> yield x
>>> yield self
>>> if self.right:
>>> for x in self.right.inorder():
>>> yield x
>>> def __iter__(self):
>>> return self.inorder()
>>> def __repr__(self, level=0, indent=" "):
>>> s = level*indent + `self.data`
>>> if self.left:
>>> s = s + "\n" + self.left.__repr__(level+1, indent) # *** Right this point ***
>>> if self.right:
>>> s = s + "\n" + self.right.__repr__(level+1, indent)
>>> return s
然后定义函数“树”
>>> def tree(List):
>>> n = len(List)
>>> if n == 0:
>>> return None
>>> i = n / 2
>>> return Tree(List[i], tree(List[:i]), tree(List[i+1:]))
最后打印二叉树
>>> t = tree('abcdef')
>>> print t
结果如下所示。
'd'
'b'
'a'
'c'
'f'
'e'
问题是为什么不在我指出的repr方法中插入“self” 。
self.left 是实例,因此可以不将'self'放入_repr _method?
提前致谢 :)