温馨提示×

python怎么调用父类构造方法

小亿
89
2024-05-28 13:29:11
栏目: 编程语言

在Python中,调用父类的构造方法可以通过super()函数实现。具体步骤如下:

  1. 在子类的__init__()方法中,使用super()函数来调用父类的构造方法。
  2. super()函数中传入当前子类的类名和self对象,这样Python会自动查找并调用父类的构造方法。

例如,假设有一个父类Animal和一个子类Dog,子类Dog想要调用父类Animal的构造方法,可以这样实现:

class Animal:
    def __init__(self, species):
        self.species = species
        print("Animal constructor called")

class Dog(Animal):
    def __init__(self, name, species):
        super().__init__(species)  # 调用父类的构造方法
        self.name = name
        print("Dog constructor called")

# 创建子类实例
dog1 = Dog("Buddy", "Canine")

在上面的例子中,子类Dog的构造方法中调用了父类Animal的构造方法,通过super().__init__(species)实现。

0