python-3.x - super() 函数是否会阻止一个公共父类的 init 函数被多次调用?
问题描述
在下面的示例中,Cat 类用于创建对象,该类对CannotSwim 和CannotFly 都使用了super()。然后这两个都将 super() 用于同一个类 Mammal()
然而,即使两者都对 Mammal 使用 super,Mammal 类也只根据输出调用一次。super() 函数是否动态地只调用它一次,因为这是多重继承的情况,还是我遗漏了什么?
简而言之,我的问题是,应该输出
猫是哺乳动物。
被打印两次,一次不能游泳和不能飞行?谢谢您的帮助!
代码:
class Animal:
def __init__(self, animalName):
print(animalName, 'is an animal.');
# Mammal inherits Animal
class Mammal(Animal):
def __init__(self, mammalName):
print(mammalName, 'is a mammal.')
super().__init__(mammalName)
# CannotFly inherits Mammal
class CannotFly(Mammal):
def __init__(self, mammalThatCantFly):
print(mammalThatCantFly, "cannot fly.")
super().__init__(mammalThatCantFly)
# CannotSwim inherits Mammal
class CannotSwim(Mammal):
def __init__(self, mammalThatCantSwim):
print(mammalThatCantSwim, "cannot swim.")
super().__init__(mammalThatCantSwim)
# Cat inherits CannotSwim and CannotFly
class Cat(CannotSwim, CannotFly):
def __init__(self):
print('I am a cat.');
super().__init__('Cat')
# Driver code
cat = Cat()
print('')
输出:
I am a cat.
Cat cannot swim.
Cat cannot fly.
Cat is a mammal.
Cat is an animal.
解决方案
推荐阅读
- android - Android BLE 和 HC-05(带 C 代码)数据发送和接收?
- java - 将 Xampp 连接到 Netbeans IDE (8.0.2)
- android - 为 editText 启动另一个活动错误消息
- javascript - 如何使用 props 更改 className ?(反应js/css)
- c# - 如何在 Asp.Net Core 3.1 中设置无效 Cookie
- sql - 存储过程中的 Openrowset 给出传输级错误
- python - 分析复杂度矩阵寻路
- php - 在触发错误的情况下 PDO 不会抛出错误
- python - 如何让模块访问非 Python 文件
- linux - 存储脚本及其输出的合适目录是什么?