最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺談Python類的單繼承相關(guān)知識(shí)

 更新時(shí)間:2021年05月12日 15:24:50   作者:Amae  
本文給大家介紹面向?qū)ο笕刂焕^承Inheritance的相關(guān)知識(shí),通過示例代碼給大家介紹了繼承、貓類、狗類不用寫代碼,直接繼承了父類的屬性和方法,具體實(shí)現(xiàn)代碼跟隨小編一起看看吧

上文我們總結(jié)過了Python多繼承的相關(guān)知識(shí),沒看過的小伙伴們也可以去看看,今天給大家介紹Python類的單繼承相關(guān)知識(shí)。

一、類的繼承

面向?qū)ο笕刂?,繼承Inheritance

人類和貓類都繼承自動(dòng)物類。

個(gè)體繼承自父母,繼承了父母的一部分特征,但也可以有自己的個(gè)性。

在面向?qū)ο蟮氖澜缰?,從父類繼承,就可以直接擁有父類的屬性和方法,這樣就可以減少代碼、多服用。子類可以定義自己的屬性和方法

class Animal:
 
    def __init__(self,name):
        self._name = name
 
    def shout(self):
        print("{}  shouts".format(self.__class__.__name__))
    @property
    def name(self):
        return self._name
 
 
class Cat(Animal):
    pass
 
 
class Dog(Animal):
    pass
 
a = Animal("monster")
a.shout()           #   Animal  shouts
 
 
cat = Cat("garfield")
cat.shout()         #   Cat  shouts
print(cat.name)     #   garfield
 
 
dog = Dog("ahuang")
dog.shout()         #   Dog  shouts
print(dog.name)     #   ahuang

上例中我們可以看出,通過繼承、貓類、狗類不用寫代碼,直接繼承了父類的屬性和方法

繼承:

  • class Cat(Animal)這種形式就是從父類繼承,括號(hào)中寫上繼承的類的列表。
  • 繼承可以讓子類重父類獲取特征(屬性、方法)

父類:

  • Animal就是Cat的父類,也稱為基類、超類

子類:

  • Cat 就是Animal的子類,也成為派生類  

二、繼承的定義、查看繼承的特殊屬性和方法

格式

class 子類 (基類1[,基類2,……]):
    語句塊

如果類定義時(shí),沒有基類列表,等同于繼承自【object】。在Python3中,【object】類是所有對(duì)象基類

查看繼承的特殊屬性和方法

特殊屬性  含義 示例
__base__  類的基類 
__bases__  類的基類元組 
__mro__  顯示方法查找順序,基類的元組 
mro()  同上  int.mro()
__subclasses__()  類的子類列表  int.__subclasses__()

三、繼承中的訪問控制

class Animal:
    __COUNT = 100
    HEIGHT = 0
 
    def __init__(self,age,weight,height):
        self.__COUNT += 1
        self.age = age
        self.__weight = weight
        self.HEIGHT = height
 
    def eat(self):
        print("{}  eat".format(self.__class__.__name__))
 
    def __getweight(self):
        print(self.__weight)
 
    @classmethod
    def showcount1(cls):
        print(cls.__COUNT)
 
    @classmethod
    def __showcount2(cls):
        print(cls.__COUNT)
 
    def showcount3(self):
        print(self.__COUNT)
 
class Cat(Animal):
    NAME = "CAT"
    __COUNT = 200
 
#a = Cat()              #   TypeError: __init__() missing 3 required positional arguments: 'age', 'weight', and 'height'
a = Cat(30,50,15)
a.eat()                 #   Cat  eat
print(a.HEIGHT)         #   15
#print(a.__COUNT)        #   AttributeError: 'Cat' object has no attribute '__COUNT'
#print(a.__showcount2)   #   AttributeError: 'Cat' object has no attribute '__showcount2'
#print(a.__getweight)    #   AttributeError: 'Cat' object has no attribute '__getweight'
a.showcount3()   #   101
a.showcount1()   #  100
print(a.NAME)    #    CAT
 
print(Animal.__dict__)  #   {'__module__': '__main__', '_Animal__COUNT': 100, 'HEIGHT': 0, '__init__': <function Animal.__init__ at 0x020DC228>, 'eat': <function Animal.eat at 0x020DC468>, '_Animal__getweight': <function Animal.__getweight at 0x02126150>, 'showcount1': <classmethod object at 0x020E1BD0>, '_Animal__showcount2': <classmethod object at 0x020E1890>, 'showcount3': <function Animal.showcount3 at 0x021264F8>, '__dict__': <attribute '__dict__' of 'Animal' objects>, '__weakref__': <attribute '__weakref__' of 'Animal' objects>, '__doc__': None}
print(Cat.__dict__)     #   {'__module__': '__main__', 'NAME': 'CAT', '_Cat__COUNT': 200, '__doc__': None}
print(a.__dict__)       #   {'_Animal__COUNT': 101, 'age': 30, '_Animal__weight': 50, 'HEIGHT': 15}

從父類繼承、自己沒有的,就可以到父類中找

私有的都是不可訪問的,但是本質(zhì)上依然是改了名稱放在這個(gè)屬性所在的類的了【__dict__】中,知道這個(gè)新民成就可以了直接找到這個(gè)隱藏的變量,這是個(gè)黑魔法慎用

總結(jié)

  • 繼承時(shí),共有的,子類和實(shí)例都可以隨意訪問;私有成員被隱藏,子類和實(shí)例不可直接訪問,當(dāng)私有變量所在類內(nèi)方法中可以訪問這個(gè)私有變量
  • Python通過自己一套實(shí)現(xiàn),實(shí)現(xiàn)和其他語言一樣的面向?qū)ο蟮睦^承機(jī)制

屬性查找順序:實(shí)例的【__dict__】------類的【__dict__】-----父類【__dict__】

如果搜索這些地方后沒有找到異常,先找到就立即返回

四、方法的重寫、覆蓋override

class Animal:
 
    def shout(self):
        print("Animal shouts")
 
class Cat(Animal):
 
    def shout(self):
        print("miao")
 
a = Animal()
a.shout()       #   Animal shouts
b  = Cat()
b.shout()       #   miao
 
print(a.__dict__)       #   {}
print(b.__dict__)       #   {}
print(Animal.__dict__)  #   {'__module__': '__main__', 'shout': <function Animal.shout at 0x017BC228>, '__dict__': <attribute '__dict__' of 'Animal' objects>, '__weakref__': <attribute '__weakref__' of 'Animal' objects>, '__doc__': None}

Cat類中shout為什么沒有打印Animal中shout的方法,方法被覆蓋了?

  • 這是因?yàn)椋?strong>屬性查找順序:實(shí)例的【__dict__】------類的【__dict__】-----父類【__dict__】

那子類如何打印父類的同命的方法

  • super()可以訪問到父類的屬性
class Animal:
 
    def shout(self):
        print("Animal shouts")
 
class Cat(Animal):
 
    def shout(self):
        print("miao")
 
    def shout(self):
        print("super():   " , super())
        print(super(Cat, self))
        super().shout()
        super(Cat,self).shout()   # 等價(jià)于super().shout()
        self.__class__.__base__.shout(self)  #不推薦使用
 
a = Animal()
a.shout()       #   Animal shouts
b  = Cat()
b.shout()       #   super():    <super: <class 'Cat'>, <Cat object>>
                #   <super: <class 'Cat'>, <Cat object>>
                #   Animal shouts
                #   Animal shouts
                #   Animal shouts
print(a.__dict__)       #   {}
print(b.__dict__)       #   {}
print(Animal.__dict__)  #   {'__module__': '__main__', 'shout': <function Animal.shout at 0x019AC228>, '__dict__': <attribute '__dict__' of 'Animal' objects>, '__weakref__': <attribute '__weakref__' of 'Animal' objects>, '__doc__': None}
print(Cat.__dict__)     #   {'__module__': '__main__', 'shout': <function Cat.shout at 0x019F6150>, '__doc__': None}
 

super(Cat,self).shout()的作用相當(dāng)于

  • 調(diào)用,當(dāng)前b的實(shí)例中找cat類基類中,shout的方法

那對(duì)于類方法和靜態(tài)方法是否也同樣適用尼?

class Animal:
    @classmethod
    def class_method(cls):
        print("class_method")
 
    @staticmethod
    def static_method():
        print("static_methond_animal")
 
class Cat(Animal):
    @classmethod
    def class_method(cls):
        super().class_method()  #   class_method
        print("class_method_cat")
 
    @staticmethod
    def static_method(cls,self):
        super(Cat,self).static_method()
        print("static_method_cat")
 
b = Cat()
b.class_method()    #   class_method
                    #   class_method_cat
b.static_method(Cat,b)
                    #   static_methond_animal
                    #   static_method_cat

這些方法都可以覆蓋,原理都一樣,屬性字典的搜索順序

五、繼承中的初始化

看以下一段代碼,有沒有問題

class A:
    def __init__(self,a):
        self.a = a
 
class B(A):
    def __init__(self,b,c):
        self.b = b
        self.c = c
 
    def printv(self):
        print(self.b)
        print(self.a)
 
a = B(100,300)
print(a.__dict__)       #   {'b': 100, 'c': 300}
print(a.__class__.__bases__)    #   (<class '__main__.A'>,)
a.printv()      #   100
                #   AttributeError: 'B' object has no attribute 'a'

上例代碼

  • 如果B類定義時(shí)聲明繼承自類A,則在B類中__bases__中是可以看到類A
  • 這和是否調(diào)用類A的構(gòu)造方法是兩回事
  • 如果B中調(diào)用了A的構(gòu)造方法,就可以擁有父類的屬性了,如果理解這一句話?
class A:
    def __init__(self,a):
        self.a = a
 
class B(A):
    def __init__(self,b,c):
        super().__init__(b+c)
        # A.__init__(self,b+c)
        self.b = b
        self.c = c
 
    def printv(self):
        print(self.b)
        print(self.a)
 
a = B(100,300)
print(a.__dict__)       #   {'a': 400, 'b': 100, 'c': 300}
print(a.__class__.__bases__)    #   (<class '__main__.A'>,)
a.printv()      #   100
                #   400

作為好的習(xí)慣,如果父類定義了__init__方法,你就改在子類__init__中調(diào)用它【建議適用super()方法調(diào)用】

那子類什么時(shí)候自動(dòng)調(diào)用父類的【__init__】方法?

例子一:【B實(shí)例的初始化會(huì)自動(dòng)調(diào)用基類A的__init__方法】

class A:
    def __init__(self):
        self.a1 = "a1"
        self.__a2 = "a2"
        print("A init")
 
class B(A):
    pass
 
b = B()     #   A init
print(b.__dict__)   #   {'a1': 'a1', '_A__a2': 'a2'}

例子二:【B實(shí)例的初始化__init__方法不會(huì)自動(dòng)調(diào)用父類的初始化__init__方法,需要手動(dòng)調(diào)用】

class A:
    def __init__(self):
        self.a1 = "a1"
        self.__a2 = "a2"
        print("A init")
 
class B(A):
    def __init__(self):
        self.b1 = "b1"
        self.__b2 = "b2"
        print("b init")
        #A.__init__(self)
 
b = B()     #   b init
print(b.__dict__)   #   {'b1': 'b1', '_B__b2': 'b2'}

那如何正確實(shí)例化?

  • 注意,調(diào)用父類的__init__方法,出現(xiàn)在不同的位置,可能導(dǎo)致出現(xiàn)不同的結(jié)果
class Animal:
    def __init__(self,age):
        print("Animal init")
        self.age = age
 
    def show(self):
        print(self.age)
 
class Cat(Animal):
    def __init__(self,age,weight):
        #調(diào)用父類的__init__方法的順序 決定show方法的結(jié)果
        super(Cat, self).__init__(age)
        print("Cat init")
        self.age = age + 1
        self.weight = weight
 
a = Cat(10,5)
a.show()        #   Animal init
                #   Cat init
                #   11

怎么直接將上例中所有的實(shí)例屬性改變?yōu)樗接袑傩裕?/p>

  • 解決辦法,一個(gè)原則,自己的私有屬性,就該自己的方法讀取和修改,不要借助其他類的方法,即父類或者派生類
class Animal:
    def __init__(self,age):
        print("Animal init")
        self.__age = age
 
    def show(self):
        print(self.__age)
 
class Cat(Animal):
    def __init__(self,age,weight):
        #調(diào)用父類的__init__方法的順序 決定show方法的結(jié)果
        super(Cat, self).__init__(age)
        print("Cat init")
        self.__age = age + 1
        self.__weight = weight
 
    def show(self):
        print(self.__age)
 
a = Cat(10,5)
a.show()        #   Animal init
                #   Cat init
                #   11
print(a.__dict__)   #   {'_Animal__age': 10, '_Cat__age': 11, '_Cat__weight': 5}

到此這篇關(guān)于淺談Python類的單繼承相關(guān)知識(shí)的文章就介紹到這了,更多相關(guān)Python類的單繼承內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python代碼實(shí)現(xiàn)備忘錄案例講解

    python代碼實(shí)現(xiàn)備忘錄案例講解

    這篇文章主要介紹了python代碼實(shí)現(xiàn)備忘錄案例講解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-07-07
  • Mac下python包管理工具pip的安裝

    Mac下python包管理工具pip的安裝

    這篇文章介紹了Mac下python包管理工具pip的安裝方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • Numpy之布爾索引的實(shí)現(xiàn)

    Numpy之布爾索引的實(shí)現(xiàn)

    本文主要介紹了Numpy之布爾索引的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • 使用python實(shí)現(xiàn)名片管理系統(tǒng)

    使用python實(shí)現(xiàn)名片管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了使用python實(shí)現(xiàn)名片管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-06-06
  • 使用python裝飾器驗(yàn)證配置文件示例

    使用python裝飾器驗(yàn)證配置文件示例

    項(xiàng)目中用到了一個(gè)WriteData的函數(shù)保存用戶填寫的配置,為了實(shí)現(xiàn)驗(yàn)證用戶輸入的需求,在不影響接口的使用的前提下,采用了python的裝飾器實(shí)現(xiàn),代碼片段演示了如何驗(yàn)證WriteData函數(shù)的輸入?yún)?shù)
    2014-02-02
  • pd.drop_duplicates刪除重復(fù)行的方法實(shí)現(xiàn)

    pd.drop_duplicates刪除重復(fù)行的方法實(shí)現(xiàn)

    drop_duplicates 方法實(shí)現(xiàn)對(duì)數(shù)據(jù)框 DataFrame 去除特定列的重復(fù)行,本文主要介紹了pd.drop_duplicates刪除重復(fù)行的方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • python實(shí)戰(zhàn)串口助手_解決8串口多個(gè)發(fā)送的問題

    python實(shí)戰(zhàn)串口助手_解決8串口多個(gè)發(fā)送的問題

    今天小編就為大家分享一篇python實(shí)戰(zhàn)串口助手_解決8串口多個(gè)發(fā)送的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • jupyter notebook如何使用matlab

    jupyter notebook如何使用matlab

    這篇文章主要介紹了jupyter notebook如何使用matlab問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • python實(shí)現(xiàn)的讀取網(wǎng)頁并分詞功能示例

    python實(shí)現(xiàn)的讀取網(wǎng)頁并分詞功能示例

    這篇文章主要介紹了python實(shí)現(xiàn)的讀取網(wǎng)頁并分詞功能,結(jié)合實(shí)例形式分析了Python使用requests模塊讀取網(wǎng)頁,以及jieba庫(kù)分詞的相關(guān)操作技巧,需要的朋友可以參考下
    2019-10-10
  • 7個(gè)關(guān)于Python的經(jīng)典基礎(chǔ)案例

    7個(gè)關(guān)于Python的經(jīng)典基礎(chǔ)案例

    這篇文章主要給大家分享 7個(gè)關(guān)于Python的經(jīng)典基礎(chǔ)案例,列表排序、調(diào)換字典鍵值、刪除列表中的重復(fù)元素、輸出質(zhì)數(shù)、判斷是一年中第幾天、猜數(shù)字、進(jìn)制轉(zhuǎn)換;,需要的朋友可以參考一下
    2021-11-11

最新評(píng)論

龙胜| 东兴市| 军事| 永昌县| 西乡县| 文昌市| 上虞市| 六枝特区| 黄浦区| 班戈县| 富阳市| 扎囊县| 上虞市| 砀山县| 德化县| 西畴县| 遂宁市| 罗定市| 周至县| 平泉县| 尖扎县| 文安县| 靖州| 大港区| 崇礼县| 鹤庆县| 韩城市| 曲水县| 长沙县| 桐庐县| 麦盖提县| 原平市| 河北区| 内江市| 玉山县| 朝阳市| 都兰县| 万宁市| 黑山县| 天柱县| 肇州县|