Python正课76 —— 在子类派生的新方法super()

本文内容皆为作者原创,如需转载,请注明出处:https://www.cnblogs.com/xuexianqi/p/12671813.html

一:方式1

指名道姓调用某一个类下的函数 ==> 不依赖于继承关系

class OldboyPeople:
    school = 'OldBoy'

    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex

    def f1(self):
        print(f'{self.name} say hello')


class Student(OldboyPeople):
    def choose_course(self):
        print('学生%s 正在选课' % self.name)


class Teacher(OldboyPeople):
    #           老师的空对象,'egon',18,'male',3000,10
    def __init__(self, name, age, sex, salary, level):
        # 方式1:# 指名道姓地跟父类OldboyPeople去要__init__
        # OldboyPeople.__init__(self, name, age, sex)
        self.salary = salary
        self.level = level

    def score(self):
        print('老师 %s 正在给学生打分' % self.name)


print(Teacher.mro())  # [<class '__main__.Teacher'>, <class '__main__.OldboyPeople'>, <class 'object'>]

二:方式2

super()调用父类提供给自己的方法 ==> 严格依赖继承关系

class OldboyPeople:
    school = 'OldBoy'

    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex

    def f1(self):
        print(f'{self.name} say hello')


class Student(OldboyPeople):
    def choose_course(self):
        print('学生%s 正在选课' % self.name)


class Teacher(OldboyPeople):
    #           老师的空对象,'egon',18,'male',3000,10
    def __init__(self, name, age, sex, salary, level):
        # 方式2:# 调用super()会得到一个特殊的对象,该对象会参照当前类的mro,去当前类的父类里找属性
        super().__init__(name, age, sex)  # 调用的是方法,自动传入对象
        self.salary = salary
        self.level = level

    def score(self):
        print('老师 %s 正在给学生打分' % self.name)


print(Teacher.mro())  # [<class '__main__.Teacher'>, <class '__main__.OldboyPeople'>, <class 'object'>]
class A:
    def test(self):
        super().test()


class B:
    def test(self):
        print('from B')


class C(A, B):
    pass


print(A.mro())  # [<class '__main__.A'>, <class 'object'>]
print(B.mro())  # [<class '__main__.B'>, <class 'object'>]
print(C.mro())  # 在代码层面A并不是B的子类,但从MRO列表来看,属性查找时,就是按照顺序C->A->B->object,B就相当于A的“父类”
# [<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>,<class ‘object'>]

obj = C()
obj.test()  # 属性查找的发起者是类C的对象obj,所以中途发生的属性查找都是参照C.mro()
# from B
class A:
    def test(self):
        print('from A')
        super().test1()


class B:
    def test1(self):
        print('from B')


class C(A, B):
    def test1(self):
        print('from C')


print(C.mro())  # 在代码层面A并不是B的子类,但从MRO列表来看,属性查找时,就是按照顺序C->A->B->object,B就相当于A的“父类”
# [<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>,<class ‘object'>]

obj = C()
obj.test()  # 属性查找的发起者是类C的对象obj,所以中途发生的属性查找都是参照C.mro()

三:使用须知

super()和之前的方法不能混用,只能用其中一种

posted @ 2020-04-10 10:37  轻描丨淡写  阅读(304)  评论(0编辑  收藏  举报