Python中的super:调用父类的构造方法

 在子类构造方法中调用父类构造方法的两种方式:

1、未绑定的方法:直接使用父类名来进行调用,即‘父类名.父类方法名(self,[参数1, 参数2,...])’

2、super(): 如果涉及多继承,该函数只能调用第一个直接父类的构造方法。super().父类方法名(self, [参数1, 参数2,...])或super(当前类名, obj).父类方法名([参数1, 参数2,...])

class People():
    def __init__(self, name):
        self.name = name
    def say(self):
        print('我是人, 名字是', self.name)

class Animal():
    def __init__(self, food):
        self.food = food
    def display(self):
        print('我是动物,我吃', self.food)

class Person(People, Animal):
    def __init__(self, name, food):
        super().__init__(name)
        Animal.__init__(self, food)  # 使用未绑定方法调用Animal类构造方法

if __name__ == '__main__':
    person = Person('张三', 'banana')
    person.say()
    person.display()

 

猜你喜欢

转载自blog.csdn.net/bb8886/article/details/131941116