当前位置: 移动技术网 > IT编程>脚本编程>Python > python super用法及原理详解

python super用法及原理详解

2020年03月09日  | 移动技术网IT编程  | 我要评论

这篇文章主要介绍了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.

参考文档

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网