类型1:父类和子类的实例变量均不需要传递

class A(object):
    def __init__(self):
        self.name = "cui"

    def get_name(self):
        return self.name


class B(A):
    def __init__(self):
        super(B,self).__init__()
        self.age = 12


b = B()

 

类型2:父类的实例变量不需要传递,子类的实例变量需要传递

class A(object):
    def __init__(self):
        self.name = "zhang"


    def get_name(self):
        return self.name


class B(A):
    def __init__(self,age):
        super(B,self).__init__()
        self.age = age


b = B("san")

 

类型3:父类有部分实例变量需要传递,子类实例变量需要传递

class A(object):
    def __init__(self,sex):
        self.name = "zhang"
        self.sex = sex


    def get_name(self):
        return self.name + self.sex


class B(A):
    def __init__(self,sex,age):
        super(B,self).__init__(sex)
        self.age = age


b = B("",12)

 

类型4:父类和子类的所有变量都需要传递

class A(object):
    def __init__(self,name,sex):
        self.name = name
        self.sex = sex


    def get_name(self):
        return self.name + self.sex


class B(A):
    def __init__(self,name,sex,age):
        super(B,self).__init__(name,sex)
        self.age = age


b = B("zhang","",12)

 

类型5:父类变量都需要传递,子类有部分实例变量需要传递

class A(object):
    def __init__(self,name,sex):
        self.name = name
        self.sex = sex


    def get_name(self):
        return self.name + self.sex


class B(A):
    def __init__(self,name,sex,age):
        super(B,self).__init__(name,sex)
        self.age = age
        self.courage = "高中"


b = B("zhang","",12)

 

类型6:父类和子类都有部分实例变量需要传递

class A(object):
    def __init__(self,name):
        self.name = name
        self.sex = ""


    def get_name(self):
        return self.name + self.sex


class B(A):
    def __init__(self,name,sex,age):
        super(B,self).__init__(name)
        self.age = age
        self.courage = "高中"


b = B("zhang","",12)

 

总结:

子类继承父类的构造函数中,在子类的构造函数中,__init__方法中的变量是包括自己和父类所有需要传递的变量,而在super().__init__方法中的参数仅仅包括父类需要传递的变量

    def __init__(self,name,sex,age):
        super(B,self).__init__(name)
        self.age = age
        self.courage = "高中"

 

posted on 2019-10-15 15:56  bainianminguo  阅读(10511)  评论(0编辑  收藏  举报