python中的继承

[亡魂溺海] 提交于 2019-12-02 18:42:15

一、单继承

子类调用父类的一个方法,可以用super():

class A(object):
    def pp(self):
        print('pp A')

class B(A):
    def pp(self):
        super().pp()
        print("pp B")
b = B()b.pp()#结果:
pp A
pp B

 

super()常用的方法是在__init__()方法中确保父类被正确的初始化了:

super(cls,inst).__init__()   #cls,init 可以省略
class A(object):
    def __init__(self):
        self.x = 1

class B(A):
    def __init__(self):
        super(B,self).__init__()
        self.x = self.x +1
        print(self.x)
b = B()#结果2

 

也可以直接调用父类的一个方法 :

A.__init__(self)
class A(object):
    def __init__(self):
        self.x = 1

class B(A):
    def __init__(self):
        A.__init__(self)
        self.x = self.x +1
        print(self.x)
b = B()#结果2

二、多继承

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!