Re: [問題]obj.__class__() 記憶體位址

看板Python作者 (洗洗睡)時間5年前 (2018/07/25 06:46), 5年前編輯推噓1(100)
留言1則, 1人參與, 5年前最新討論串2/2 (看更多)
※ 引述《LouisFFs ()》之銘言: : --------------------------------- : class Something: : pass : print('define a class:') : print(Something) #(1) : print(type(Something)) : print('create an object:') : s=Something() : print(s) #(2) : print(type(s)) : print('__class__ read data:') : print(s.__class__) #(3) : print(s.__class__()) #(4) : ----------------------------------- : output: : define a class: : <class 'Something'> : <class 'type'> : create an object: : <Something object at 0x0238DD70> : <class 'Something'> : __class__ read data: : <class 'Something'> : <Something object at 0x0239F730> : ------------------------------------ 幾個物件的關係是這樣,箭頭代表實例化: type --> Something --> s 1. Something是type的一個instance,s是Something的instance。 type是一切的根源:type是type的instance。 2. type其實是一個metaclass。一個metaclass實例化後是一個class。 其實我們也可以直接呼叫type來產生一個class。 而因為所有東西都是物件,Something和s如果這樣看的話沒有什麼不同 (所以我想你說的"等價一個命名空間"這個概念應該是不正確的)。 3. 用obj.__class__可以得到obj的class,s.__class__()其實等同於Something(), 更進一步也等同於Something.__call__()。 因此,#(2)和#(4)是兩個不同的Something instance,所以記憶體不同。 4. 但是,不要用obj.__class__來檢查obj是哪一個class。 請用isinstance(s, Something),它可以幫你檢查繼承。 ``` >>> Something = type('Something', (), {}) >>> s = Something() >>> type.__class__ == type True >>> Something.__class__ == type True >>> isinstance(Something, type) True >>> s.__class__ == Something True >>> isinstance(s, Something) True ``` ※ 編輯: ThxThx (114.44.199.194), 07/25/2018 06:48:05

07/25 09:32, 5年前 , 1F
謝謝你! 理解了!!
07/25 09:32, 1F
文章代碼(AID): #1RLwmzI_ (Python)
文章代碼(AID): #1RLwmzI_ (Python)