Python多继承三种情况


Tips:

  1. 知道super.__init__和类名.__init__两者的区别
  2. 默认对python多继承和继承有一定的基础
  3. 默认知道继承__mro__

Case1(基类都未考虑多继承的情况)

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

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

class Student(Person, Human): # 基类都独立未考虑多继承情况
    def __init__(self, name ,sex):
        Person.__init__(self,name)
        Human.__init__(self,sex)

if __name__ == '__main__':
    a = Student('xiaoming','female')
    print(a.name)
    print(a.sex)
class Person(object):
    def __init__(self, name, *args):
        self.name = name

class Human(object):
    def __init__(self, sex, *args):
        self.sex = sex

class Student(Person, Human):
    def __init__(self,name, sex):
        super().__init__(name, sex)


if __name__ == '__main__':
    a = Student('xiaoming', 'female')
    print(a.name)
    print(a.sex) # error》'Student' object has no attribute 'sex'
#这里会报错,根据mro方法解析顺序,Person被初始化后,没有继续调用super()进行初始化 Human,拿不到sex属性?(此处是我自己的理解,欢迎讨论。)

Case 2(混合继承类)

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

class Human(object):
    def __init__(self, sex, *agrs):
        self.sex = sex
        super().__init__(*agrs)

class Student(Human, Person): # 顺序必须对,不然Person不能被初始化
    def __init__(self,sex, name):
        super().__init__(sex, name)

if __name__ == '__main__':
    a = Student( 'female', 'xiaoming')
    print(a.name)
    print(a.sex)

Case 3(多继承设计类)

class Person(object):
    def __init__(self, name,*args):
        self.name = name
        super().__init__(*args)

class Human(object):
    def __init__(self, sex, *args):
        self.sex = sex
        super().__init__()

class Student(Person, Human):
    def __init__(self, name, sex):
        super().__init__(name, sex)

if __name__ == '__main__':
    a = Student( 'female', 'xiaoming')
    print(a.name)
    print(a.sex)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值