在多继承的情况下,如果子类没有重写__init__()方法,则会默认调用第一个父类的__init__()方法。如果想要使用其他父类的属性,可以使用super()函数来调用其他父类的方法。

下面是一个示例代码:

class Parent1:
    def __init__(self):
        self.name = "Parent1"
        self.age = 10

class Parent2:
    def __init__(self):
        self.name = "Parent2"
        self.gender = "Male"

class Child(Parent1, Parent2):
    def __init__(self):
        super().__init__()  # 调用第一个父类的__init__()方法
        self.school = "ABC School"

child = Child()
print(child.name)   # 输出:Parent1
print(child.age)    # 输出:10
print(child.gender) # 输出:Male
print(child.school) # 输出:ABC School

在上面的示例中,Child类继承了Parent1Parent2两个父类,但是没有重写__init__()方法。当创建Child对象时,会调用Parent1__init__()方法,因此name属性的默认值为"Parent1",而age属性的默认值为10。使用super().__init__()调用第一个父类的__init__()方法后,Child类还可以访问Parent2的属性gender,并且Child类自己定义了属性school

注意:在使用多继承时,需要注意父类的顺序,因为super()函数会按照父类的顺序依次调用__init__()方法。如果想要修改默认调用的父类,可以调整父类的顺序。

python 多继承时初始化属性默认使用的父类的属性

原文地址: https://www.cveoy.top/t/topic/igPR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录