---------Python基础编程---------
Author : AI菌
【内容讲解】
【代码演示】
""" 1.多继承的格式: class 子类名(父类1, 父类2, ...): 子类中的代码 2.如果继承了多个父类,且父类都有同名方法,则默认只执行第一个父类的 3. 如果要调用父类中指定的方法, 通过下面格式调用: 父类名.方法名(self, 实参1,实参2,...) 4. 调用时,参数self必须要加上,否则报错 """ class A: def __init__(self, a): self.a = a def methodA(self): print("---------methodA---------") def show(self): print("show from A") class B: def __init__(self, b): self.b = b def methodB(self): print("---------methodB---------") def show(self): print("show from B") # 让C类同时继承A,B两个父类 class C(A, B): # 为了继承A,B两个父类中的属性,需要重写init方法,在方法中调用两个父类中的init方法 def __init__(self, a, b): # 调用A,B类中的init方法 A.__init__(self, a) B.__init__(self, b) def test(self): # 调用A类中的show方法 # self.show() A.show(self) # show from A # 调用B类中的show()方法,self必须要加上,否则报错 B.show(self) # show from B c = C("a的属性", "b的属性") print(c.a) # a的属性 print(c.b) # b的属性 c.methodA() # ---------methodA--------- c.methodB() # ---------methodB--------- # 如果继承了多个父类,且父类都有同名方法,则默认只执行第一个父类的 # 执行A类的show()方法,不会执行B类的show()方法 c.show() # show from A # 调用test()方法,间接调用B类中的show()方法 # 调用B类中的show()方法,self必须要加上,否则报错 c.test()
【往期精彩】
▷【Python基础编程196 ● 读取文件的4种方式】
▷【Python基础编程197 ● 读取文件的4种方式】
▷【Python基础编程198 ● 读取文件的4种方式】
▷【Python基础编程199 ● Python怎么读/写很大的文件】
▷【Python基础编程200 ● 读取文件的4种方式】
▷【Python基础编程201 ● 读取文件的4种方式】
▷【Python基础编程202 ● 读取文件的4种方式】
▷【Python基础编程203 ● 读取文件的4种方式】
【加群交流】