我寫了下面的代碼:意外的結果在Python類初始化
class node:
def __init__(self, title, series, parent):
self.series = series
self.title = title
self.checklist = []
if(parent != None):
self.checklist = parent.checklist
self.checklist.append(self)
當我創建的對象是這樣的:
a = node("", s, None)
b = node("", s, a)
print a.checklist
出乎意料的是,它顯示了A和B的對象作爲print語句的輸出。 我是python的新手。所以,可能有一些愚蠢的錯誤。
謝謝。
'self.checklist = parent.checklist'如果parent = None應該引發AttributeError,我認爲它應該在if語句中。而且,使用'parent不是'而不是'!=',並且不要在if語句(帶有一個條件)時使用parantheses。 – utdemir
對不起。這是一個複製錯誤。糾正。 – mihsathe