python super用法及原理详解

yipeiwu_com5年前Python基础

这篇文章主要介绍了python super用法及原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

概念

super作为python的内建函数。主要作用如下:

  • 允许我们避免使用基类
  • 跟随多重继承来使用

实例

在单个继承的场景下,一般使用super来调用基类来实现:
下面是一个例子:

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()

输出结果:

➜ super git:(master) ✗ py super_script.py

Dog has four legs.

Dog is a warm-blooded animal.

super在多重继承里面的使用:

下面是一个例子:

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')

输出结果:

➜ 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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

详解pandas中MultiIndex和对象实际索引不一致问题

在最新版的pandas中(不知道之前的版本有没有这个问题),当我们对具有多层次索引的对象做切片或者通过df[bool_list]的方式索引的时候,得到的新的对象尽管实际索引已经发生了改变...

Python排序搜索基本算法之选择排序实例分析

Python排序搜索基本算法之选择排序实例分析

本文实例讲述了Python排序搜索基本算法之选择排序。分享给大家供大家参考,具体如下: 选择排序就是第n次把序列中最小的元素排在第n的位置上,一旦排好就是该元素的绝对位置。代码如下:...

Python re 模块findall() 函数返回值展现方式解析

findall 函数: 在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。 注意: match 和 search 是匹配一次 findall...

python验证码识别教程之滑动验证码

前言 上篇文章记录了2种分割验证码的方法,此外还有一种叫做”滴水算法”(Drop Fall Algorithm)的方法,但本人智商原因看这个算法看的云里雾里的,所以今天记录滑动验证码的处...

python3编码问题汇总

python3编码问题汇总

这两天写了个监测网页的爬虫,作用是跟踪一个网页的变化,但运行了一晚出现了一个问题。。。。希望大家不吝赐教! 我用的是python3,错误在对html response的decode时抛出...