练习题:89
目录
Python题目
题目
题目分析
代码实现
代码解释
定义父类 Animal:
定义子类 Dog:
创建 Dog 类的实例:
运行思路
结束语
Python题目
题目
使用super()函数调用父类的构造函数。
题目分析
在 Python 的面向对象编程中,当一个子类继承自父类时,有时需要在子类的构造函数中调用父类的构造函数,以确保父类的初始化逻辑被执行。super()
函数就是用于实现这一目的的工具,它可以返回一个代理对象,该对象会将方法调用委托给父类,从而方便地调用父类的方法,包括构造函数。
代码实现
class Animal:
def __init__(self, species):
self.species = species
print(f"An {self.species} is created.")
class Dog(Animal):
def __init__(self, name, species="Dog"):
super().__init__(species)
self.name = name
print(f"A dog named {self.name} is created.")
# 创建 Dog 类的实例
dog = Dog("Buddy")
代码解释
-
定义父类
Animal
:
class Animal:
def __init__(self, species):
self.species = species
print(f"An {self.species} is created.")
Animal
类有一个构造函数 __init__
,它接受一个参数 species
,并将其赋值给实例属性 self.species
,然后打印一条创建动物的信息。
-
定义子类
Dog
:
class Dog(Animal):
def __init__(self, name, species="Dog"):
super().__init__(species)
self.name = name
print(f"A dog named {self.name} is created.")
Dog
类继承自 Animal
类。在 Dog
类的构造函数中:
super().__init__(species)
:使用super()
函数调用父类Animal
的构造函数,并将species
作为参数传递给它,这样可以确保父类的初始化逻辑被执行。self.name = name
:为Dog
类的实例添加一个新的属性name
。- 打印一条创建狗的信息。
-
创建
Dog
类的实例:
dog = Dog("Buddy")
创建一个 Dog
类的实例 dog
,并将名字 "Buddy"
传递给构造函数。
运行思路
程序开始运行后,当执行 dog = Dog("Buddy")
时,会调用 Dog
类的构造函数。在 Dog
类的构造函数中,首先执行 super().__init__(species)
,这会调用父类 Animal
的构造函数,Animal
类的构造函数将 species
(这里是 "Dog"
)赋值给 self.species
并打印创建动物的信息。然后,Dog
类的构造函数继续执行,将 "Buddy"
赋值给 self.name
并打印创建狗的信息。
结束语
super()
函数在 Python 的类继承中非常有用,它可以帮助我们避免代码重复,确保父类的初始化逻辑被正确执行。通过使用 super()
函数,我们可以更好地实现代码的复用和扩展。在实际开发中,当子类需要在自身的构造函数中调用父类的构造函数时,super()
函数是一个很好的选择。你可以根据不同的需求定义更多的父类和子类,并灵活运用 super()
函数来处理类之间的继承关系。