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

Python重寫父類的三種方法小結(jié)

 更新時(shí)間:2023年03月28日 11:05:43   作者:小Pawn爺  
本文主要介紹了Python重寫父類的三種方法小結(jié),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

1.基礎(chǔ)應(yīng)用

class Animal(object):
? ? def eat(self):
? ? ? ? print("動(dòng)物吃東西")


class Cat(Animal):
? ? def eat(self):
? ? ? ? print("貓吃魚")
? ? ? ? # 格式一:父類名.方法名(對(duì)象)
? ? ? ? Animal.eat(self)
? ? ? ? # 格式二:super(本類名,對(duì)象).方法名()
? ? ? ? super(Cat, self).eat()
? ? ? ? # 格式三:super()方法名()
? ? ? ? super().eat()


cat1 = Cat()
cat1.eat()
print(cat1)

2.實(shí)際應(yīng)用

#用元類實(shí)現(xiàn)單例模式
class SingletonType(type):
? ? instance = {}

? ? def __call__(cls, *args, **kwargs):
? ? ? ? if cls not in cls.instance:
? ? ? ? ? ? # 方式一:
? ? ? ? ? ? # cls.instance[cls] = type.__call__(cls, *args, **kwargs)
? ? ? ? ? ? # 方式二
? ? ? ? ? ? # cls.instance[cls] = super(SingletonType, cls).__call__(*args, **kwargs)
? ? ? ? ? ? # 方式三
? ? ? ? ? ? cls.instance[cls] = super().__call__(*args, **kwargs)
? ? ? ? return cls.instance[cls]


class Singleton(metaclass=SingletonType):
? ? def __init__(self, name):
? ? ? ? self.name = name


s1 = Singleton('1')
s2 = Singleton('2')
print(id(s1) == id(s2))

3.注意

1.當(dāng)一個(gè)類存在多繼承時(shí),它繼承的多個(gè)父類有相同的父類A,在重寫其父類時(shí)需要注意

方法一:父類名.方法名(對(duì)象)

  • 父類A會(huì)被調(diào)用多次(根據(jù)繼承的個(gè)數(shù))
  • 重寫父類時(shí)根據(jù)需要傳遞所需要的參數(shù)

方法二:super(本類名,對(duì)象).方法名()

  • 父類A也只會(huì)被調(diào)用一次
  • 重寫父類方法必須傳遞所有參數(shù)

2.當(dāng)一個(gè)類存在繼承,且已經(jīng)在子類中重寫相應(yīng)的變量,改變父類的變量不會(huì)對(duì)子類有影響

class Parent(object):
? ? x = 1

class Child1(Parent):
? ? pass

class Child2(Parent):
? ? pass

print(Parent.x, Child1.x, Child2.x)
Child1.x = 2
print(Parent.x, Child1.x, Child2.x)
Parent.x = 3
print(Parent.x, Child1.x, Child2.x)

輸出結(jié)果

1 1 1
1 2 1
3 2 3

到此這篇關(guān)于Python重寫父類的三種方法小結(jié)的文章就介紹到這了,更多相關(guān)Python重寫父類內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

伊通| 墨玉县| 建昌县| 新和县| 襄樊市| 淳安县| 汤阴县| 澎湖县| 芦溪县| 醴陵市| 盐山县| 丰宁| 苗栗市| 辛集市| 吴桥县| 宿松县| 克什克腾旗| 乌海市| 师宗县| 南雄市| 梓潼县| 镇坪县| 凤山市| 简阳市| 淮滨县| 汉寿县| 黑龙江省| 沙河市| 定西市| 翁源县| 古交市| 毕节市| 宝丰县| 台州市| 达孜县| 广宗县| 汝阳县| 聂拉木县| 德兴市| 浦县| 宣城市|