[英]Strange Python class behavior
我創建了一個簡單的類來管理相關對象的樹:
class node(object):
children = list([])
def __init__(self, ID, *children):
self.ID = ID
for c in children:
self.children.append(c)
def add(self, *children ):
for c in children:
self.children.append(c)
def __str__(self):
return self.ID
def __repr__(self):
print self.ID, len(self.children)
root = node('1')
root.add( node('1.1', node('1.1.1')),
node('1.2'))
for c in root.children:
print c
我越來越:
1.1.1
1.1
1.2
但是我期望只有1.1和1.2。 我怎么了
謝謝,德米特里
self.children
引用的是node.children
,它是一個類變量。 在該類的所有實例之間共享的列表只有一個實例。
您需要使其成為實例變量:
class Node(object):
def __init__(self, id, *children):
self.children = []
同樣, __str__
和__repr__
應該返回遵循某種格式的字符串。
將children = list([])
放在__init__
方法內,如下所示:
def __init__(self, ID, *children):
self.ID = ID
self.children = []
for c in children:
self.children.append(c)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.