栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python多继承三种情况

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python多继承三种情况

Python多继承三种情况
  • Case1(基类都未考虑多继承的情况)
  • Case 2(混合继承类)
  • Case 3(多继承设计类)

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)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/283421.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号