在此代碼:Python 2.7版:奇怪的構造函數的行爲:改變錯誤的領域
# coding=utf-8
def print_tree(node, tree=0):
print(u"|---" * tree + u"-> %s" % node)
for kid in node.children:
print_tree(kid, tree + 1)
class Person(object):
parent = None
first_name = None
last_name = None
children = []
def __str__(self):
return '%s %s' % (self.first_name, self.last_name)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
def __init__(self, first_name, last_name, parent=None):
if parent is not None:
if not isinstance(parent, Person):
raise AttributeError('`parent` is not `Person` type!')
self.parent = parent
self.parent.children.append(self)
self.first_name = first_name
self.last_name = last_name
#self.children = []
root = Person('Alan', 'Smith')
p1 = Person('Barbara', 'Smith', root)
p2 = Person('Basia', 'Smith', root)
p3 = Person('Bary', 'Smith', root)
print_tree(root)
如果我刪除從#self.children = []
例如評論工作正常。但我不明白爲什麼我必須添加這一行?
在調試器中我發現,線self.parent.children.append(self)
增加self
也爲self.children
爲什麼?
Lol,3年的自學Python,bilion代碼行和你破壞了我的基本知識:D – WBAR 2013-02-21 15:35:28
對不起;如果你使用過其他語言,這並不是非常明顯,但它是有意義的(班級屬性定義級別)。 – 2013-02-21 21:01:10