结论
1.多继承的格式:
class 子类名(父类1, 父类2, …):
子类中的代码
2.如果继承了多个父类,且父类都有同名方法,则默认只执行第一个父类的
继承两个类
class A:
def get(self):
print("get A")
class B:
def get(self):
print("get B")
class C(A, B):
def __init__(self):
print("class C")
c = C()
c.get()
输出:
F:\PyProject\test\venv\Scripts\python.exe F:/PyProject/test/t.py
class C
get A
另一种情况:
class A:
def __init__(self):
print("class A")
class B:
def __init__(self):
print("class B")
class C(A, B):
def get(self):
print("get C")
c = C()
c.get()
输出
F:\PyProject\test\venv\Scripts\python.exe F:/PyProject/test/t.py
class A
get C
继承顺序交换
class A:
def get(self):
print("get A")
class B:
def get(self):
print("get B")
class C(B, A):
def __init__(self):
print("class C")
c = C()
c.get()
输出
F:\PyProject\test\venv\Scripts\python.exe F:/PyProject/test/t.py
class C
get B
不重复的函数
class A:
def get(self):
print("get A")
def func1(self):
print("func1")
class B:
def get(self):
print("get B")
def func2(self):
print("func2")
class C(B, A):
def __init__(self):
print("class C")
def func3(self):
print("func3")
c = C()
c.func1()
c.func2()
c.func3()
输出:
F:\PyProject\test\venv\Scripts\python.exe F:/PyProject/test/t.py
class C
func1
func2
func3