Fork me on GitHub

概念

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.

参考文档

posted on   虚生  阅读(669)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
历史上的今天:
2018-12-21 2018,你过的好吗?
2018-12-21 shell cut 应用实战
2018-12-21 shell 问题备忘
2017-12-21 python中基于queue的打印机仿真算法
2017-12-21 Python random模块(获取随机数)常用方法和使用例子
2017-12-21 python中不同文件中函数和类的调用
点击右上角即可分享
微信分享提示