Python 继承
1.Python中继承的概念
2.多继承
3.子类重写父类的同名属性和方法
4.子类调用父类同名属性和方法
1.Python中继承的概念
面向对象三大特性:封装、继承、多态
在程序中,继承描述的是多个类之间的所属关系。
如果一个类A里面的属性和方法可以复用,则可以通过继承的方式,传递到类B里。
那么类A就是基类,也叫做父类;类B就是派生类,也叫做子类。
(单继承)
# 父类
class A(object):
def __init__(self):
self.num = 10
def print_num(self):
print(self.num + 10)
# 子类
class B(A):
pass
b = B()
print(b.num) # 继承父类之后,可以使用父类的属性和方法
b.print_num()
result:
10
20
2.多继承
多继承就是子类继承多个父类,也继承了所有父类的属性和方法
如果多个父类中有同名的 属性和方法,则默认使用第一个父类的属性和方法
多个父类中,不重名的属性和方法,不会有任何影响。
# 父类
class A(object):
def __init__(self):
self.money = 100
def hobby(self):
print("喜欢游戏")
# 父类
class B(object):
def __init__(self):
self.money = 200
self.height = 170
def hobby(self):
print("喜欢运动")
def other(self):
print("身高:170")
# 子类
class C(A, B):
pass
user = C()
# 多个父类中有同名的 属性和方法,则默认使用第一个父类的属性和方法
# 所以会打印 A父类的属性和方法
print(user.money)
user.hobby()
# 多个父类中,不重名的属性和方法,不会有任何影响
# 因为A父类没有other这个方法,只有B父类有这个方法,所以会打印B父类的other方法
user.other()
result:
100
喜欢游戏
身高:170
3.子类重写父类的同名属性和方法
子类重写父类的同名方法和属性:
如果子类和父类的方法名和属性名相同,则默认使用子类的
# 父类
class A(object):
def __init__(self):
self.money = 100
def hobby(self):
print("喜欢游戏")
# 子类
class C(A):
def __init__(self):
self.money = 300
def hobby(self):
print("喜欢跑步")
user = C()
# 子类和父类有同名属性、方法时,则默认使用子类的属性、方法
print(user.money)
user.hobby()
result:
300
喜欢跑步
4.子类调用父类同名属性和方法
1.通过 super().方法名() 去执行同名的 父类的方法
2.执行父类的 同名属性-->先执行 super().__init__(),然后再直接使用 同名的属性,去执行父类
# 父类
class A(object):
def __init__(self):
self.money = 100
self.height = 170
def hobby(self):
print("喜欢游戏")
# 子类
class C(A):
def __init__(self):
self.money = 300
def hobby(self):
print("喜欢跑步")
def run_father(self):
super().hobby()
print("")
print("使用子类的属性")
print(self.money)
print("")
print("通过super().__init__(),去使用父类的属性")
super().__init__()
print(self.money)
user = C()
user.run_father()
result:
喜欢游戏
使用子类的属性
300
通过super().__init__(),去使用父类的属性
100
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。
文章标题:Python 继承
本文作者:伟生
发布时间:2021-06-06, 22:33:25
最后更新:2021-06-07, 12:03:17
原始链接:http://yoursite.com/2021/06/06/basic_09_jicheng/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。