python創建一個類很簡單只需要定義它就可以了.
class Cat: pass
就像這樣就可以了,通過創建子類我們可以繼承他的父類(超類)的方法。這里重新寫一下cat
class Cat: name = 'cat' class A(Cat): pass print A.name # cat
經典類
我們也可以這樣,讓A多繼承。
class Cat: name = 'cat' class Dog: name = 'dog' class A(Cat, Dog): pass print A.name # cat
如果Cat類沒有name屬性呢?
class Cat: pass ... print A.name # dog
A就會在其他的父類中找name這個屬性。如果繼承的兩個父類都是繼承自Animal類而Animal類也有name屬性呢?
class Animal: name = 'animal' class Cat(Animal): pass class Dog(Animal): name = 'dog' class A(Cat, Dog): pass print A.name # animal
這樣A就不會在Dog類中找而是會在Animal上找到name, 這種類叫經典類。類的解析順序是一種從左到右深度優先的搜索。也就是A?C> Cat?C> Animal ?C> Dog。
新式類
python還有一種創建類的方式,就是使用新式類(建議使用), 都繼承自object這個基類, 新式類的搜索規則是從左到右逐級查詢。也就是A?C> Cat ?C> Dog ?C> Animal。
class Cat(object): pass
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
