如何在python中使用super方法-创新互联

如何在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.

关于如何在python中使用super方法问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。

分享标题:如何在python中使用super方法-创新互联
URL分享:https://www.cdcxhl.com/article18/cscogp.html

成都网站建设公司_创新互联,为您提供网站策划小程序开发网站收录外贸网站建设Google搜索引擎优化

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网页设计公司