python super用法及原理詳解
這篇文章主要介紹了python super用法及原理詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
概念
super作為python的內(nèi)建函數(shù)。主要作用如下:
- 允許我們避免使用基類
- 跟隨多重繼承來使用
實(shí)例
在單個(gè)繼承的場景下,一般使用super來調(diào)用基類來實(shí)現(xiàn):
下面是一個(gè)例子:
class Mammal(object):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')
class Dog(Mammal):
def __init__(self):
print('Dog has four legs.')
super().__init__('Dog')
d1 = Dog()
輸出結(jié)果:
➜ super git:(master) ✗ py super_script.py
Dog has four legs.
Dog is a warm-blooded animal.
super在多重繼承里面的使用:
下面是一個(gè)例子:
class Animal:
def __init__(self, animalName):
print(animalName, 'is an animal.');
class Mammal(Animal):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')
super().__init__(mammalName)
class NonWingedMammal(Mammal):
def __init__(self, NonWingedMammalName):
print(NonWingedMammalName, "can't fly.")
super().__init__(NonWingedMammalName)
class NonMarineMammal(Mammal):
def __init__(self, NonMarineMammalName):
print(NonMarineMammalName, "can't swim.")
super().__init__(NonMarineMammalName)
class Dog(NonMarineMammal, NonWingedMammal):
def __init__(self):
print('Dog has 4 legs.');
super().__init__('Dog')
d = Dog()
print('')
bat = NonMarineMammal('Bat')
輸出結(jié)果:
➜ super git:(master) ✗ py super_muli.py Dog has 4 legs. Dog can't swim. Dog can't fly. Dog is a warm-blooded animal. Dog is an animal. Bat can't swim. Bat is a warm-blooded animal. Bat is an animal.
參考文檔
https://www.programiz.com/python-programming/methods/built-in/super
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python中super()函數(shù)的理解與基本使用
- 詳解python的super()的作用和原理
- Python類的繼承super相關(guān)原理解析
- python super()函數(shù)的基本使用
- Python類super()及私有屬性原理解析
- Python super()函數(shù)使用及多重繼承
- Python super()方法原理詳解
- python super函數(shù)使用方法詳解
- python類中super() 的使用解析
- 使用 Supervisor 監(jiān)控 Python3 進(jìn)程方式
- Python高級編程之繼承問題詳解(super與mro)
- Python 繼承,重寫,super()調(diào)用父類方法操作示例
- python3中類的繼承以及self和super的區(qū)別詳解
- Python中的super()面向?qū)ο缶幊?/a>
相關(guān)文章
Python+tkinter實(shí)現(xiàn)高清圖片保存
作為愛玩電腦的你是不是也需要經(jīng)常更換一下自己的電腦壁紙呢?但是在網(wǎng)上有很多心儀的圖片想要保存下來,如果一張張的去保存那效率又低。所以本文用Python寫一個(gè)保存圖片的功能,把我們的圖片給保存到我們的電腦,需要的可以參考一下2022-03-03
Python基于多線程操作數(shù)據(jù)庫相關(guān)問題分析
這篇文章主要介紹了Python基于多線程操作數(shù)據(jù)庫相關(guān)問題,結(jié)合實(shí)例形式分析了Python使用數(shù)據(jù)庫連接池并發(fā)操作數(shù)據(jù)庫避免超時(shí)、連接丟失相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-07-07
Python正則替換字符串函數(shù)re.sub用法示例
這篇文章主要介紹了Python正則替換字符串函數(shù)re.sub用法,結(jié)合實(shí)例形式分析了正則替換字符串函數(shù)re.sub的功能及簡單使用方法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2017-01-01
基于python實(shí)現(xiàn)對文件進(jìn)行切分行
這篇文章主要介紹了基于python實(shí)現(xiàn)對文件進(jìn)行切分行,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
pandas時(shí)間序列之pd.to_datetime()的實(shí)現(xiàn)
本文主要介紹了pandas時(shí)間序列之pd.to_datetime()的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧<BR>2022-06-06

