Re: [問題] 繼承List的問題

看板Python作者 (荒圍!定厝!賊!妹!)時間11年前 (2013/03/05 13:31), 編輯推噓0(002)
留言2則, 2人參與, 最新討論串3/3 (看更多)
※ 引述《imasa (便當俠)》之銘言: : class A: : m_list = [] : m_number = 1 : ... : class B(A): : def __init__ (self): : A.__init__(self) : pass : ... : class C(A): : def __init__ (self): : A.__init__(self) : pass : ... : 我發現B和C繼承A之後 m_number 這兩個class各自都繼承了一份 : 我可以個別操作他們 : 但是繼承下來的 m_list 卻都是A的 m_list : 我 print B 或 C 的self.list,他們的address都是相同的 : 請問這是正常的嗎? : 如果是正常的話 : 那想要繼承的B和C Class都各自有自己的一份 m_list 該怎麼作呢? : p.s.: 我是使用Python2.7.3 部分恕刪。 還滿不正常的,我的A要繼承object才能在B和C用__init__,直接貼你的code跑會有error 總之正常的繼承像這樣: class A(object): def __init__(self): self.m_list = [] self.m_number = 1 class B(A): def __init__ (self): super(B, self).__init__() class C(A): def __init__ (self): super(C, self).__init__() b=B() c=C() print b.m_list is c.m_list # >>> False ################################################ super是built-in function, 簡單來說會回傳參數的parent class讓你呼叫method。(原諒我這句話有許多語病) 你的code問題在於m_list = [] 與 self.m_list = []的差別, 前者只是建立A裡的區域變數,接著B和C繼承了A,也跟著繼承區域變數, 因此你呼叫b.m_list有東西並不是__init__的功勞,那是天生的, 所以m_list理所當然address是相同的,因為你繼承你爸的房子就可以說你有房子, 但你的房子和你爸的房子是同一棟啊。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.109.196.214 ※ 編輯: ck574b027 來自: 140.109.196.214 (03/05 13:53)

03/05 15:39, , 1F
不好意思是我打錯了,實際上是self.m_list跟self.m_enab才對
03/05 15:39, 1F

03/05 16:02, , 2F
那也很怪啊,直接用self不會跑出not defined?
03/05 16:02, 2F
文章代碼(AID): #1HDOCNY5 (Python)
文章代碼(AID): #1HDOCNY5 (Python)