- python中子类继承父类的所有类属性和方法,父类的构造方法子类同样会继承
如果子类继承多个父类,则子类对象在调用该方法时,会优先选择排在最前面的父类中的实例方法,构造方法也是如此
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)
#People中的 name 属性和 say() 会遮蔽 Animal 类中的
class Person(People, Animal):
pass
per = Person("zhangsan")
per.say() # 我是人,名字为: zhangsan
per.display() # 报错,因为display()方法中,需要用到food属性,但是Person类只调用了People的构造函数,在创建per对象时,Animal类的构造函数未执行
针对以上情况,可以在子类中重写父类的构造方法
调用父类构造方法的方式有 2 种
1、使用super()函数
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):
# 调用第一个父类People的构造方法
super().__init__(name)
# 调用其它父类构造方法,需要手动给self传值
Animal.__init__(self,food)
per = Person("张三","鸡肉")
per.say()
per.display()