1、子类可以调用父类的方法或属性。
class Parent():
def hello(self):
print('正在调用父类方法')
# Child继承Parent
class Child(Parent):
pass
p=Parent()
p.hello()
c=Child()
c.hello()
运行结果:
正在调用父类方法
正在调用父类方法
2、如果子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法或属性。
class Parent():
def hello(self):
print('正在调用父类方法')
# Child继承Parent
class Child(Parent):
def hello(self):
print('正在调用子类方法')
p=Parent()
p.hello()
c=Child()
c.hello()
运行结果:
正在调用父类方法
正在调用子类方法
3、自动覆盖会带来一些问题
class Parent():
def __init__(self):
self.name = '老王'
self.family_property = 1e6
def hello(self):
print('正在调用父类方法')
# Child继承Parent
class Child(Parent):
def __init__(self):
self.name = '小王'
def hello(self):
print('正在调用子类方法')
c=Child()
print(c.name)
print(c.family_property)
运行结果:
小王
Traceback (most recent call last):
File “C:\Users\86177\Desktop\temp.py”, line 17, in
print(c.family_property)
AttributeError: ‘Child’ object has no attribute ‘family_property’
解决办法:再次调用父类中的初始化函数
class Parent():
def __init__(self):
self.name = '老王'
self.family_property = 1e6
def hello(self):
print('正在调用父类方法')
# Child继承Parent
class Child(Parent):
def __init__(self):
# 再次调用父类中的初始化函数
Parent.__init__(self)
self.name = '小王'
def hello(self):
print('正在调用子类方法')
c=Child()
print(c.name)
print(c.family_property)
运行结果:
小王
1000000.0
4、多重继承的话,如何解决自动覆盖带来的问题
4.1 直接给定父类名字
class Parent():
def __init__(self):
self.name = '老王'
self.family_property = 1e6
def hello(self):
print('正在调用父类方法')
class School():
def __init__(self):
self.name = '北京大学'
self.school_address = '北京'
def open(self):
print('开学喽')
# Child继承Parent和School
class Child(Parent,School):
def __init__(self):
# 再次调用父类中的初始化函数
Parent.__init__(self)
School.__init__(self)
self.name = '小王'
def hello(self):
print('正在调用子类方法')
c=Child()
print(c.name)
print(c.family_property)
c.open()
print(c.school_address)
运行结果:
小王
1000000.0
开学喽
北京
4.2 使用super函数,不用直接给定父类名字。这样做会有一个问题,如果多个父类中有同名的方法,前面父类的方法会覆盖后面父类的方法,所以一般不用多重继承。
class Parent():
def __init__(self):
self.name = '老王'
self.family_property = 1e6
def hello(self):
print('正在调用父类方法')
class School():
def __init__(self):
self.name = '北京大学'
self.school_address = '北京'
def open(self):
print('开学喽')
# Child继承Parent和School
class Child(Parent,School):
def __init__(self):
# 再次调用父类中的初始化函数
super().__init__()
self.name = '小王'
def hello(self):
print('正在调用子类方法')
c=Child()
print(c.name)
print(c.family_property)
c.open()
print(c.school_address)
运行结果:
小王
1000000.0
开学喽
Traceback (most recent call last):
File “C:\Users\86177\Desktop\temp.py”, line 28, in
print(c.school_address)
AttributeError: ‘Child’ object has no attribute ‘school_address’