首页 > 解决方案 > 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.

标签: python-3.xclassoopinheritance

解决方案


推荐阅读