(资料图片仅供参考)

一、重用父类方法

1 与继承没有关系的重用

class A:    def __init__(self,name,age):        self.name=name        self.age=age        class Person:    school = "oldboy"    def __init__(self,name,age):        self.name=name        self.age=age    def study(self):        print("study....")class Teacher(Person):    def __init__(self,name,age,level):        A.__init__(self,name,age)        self.level=levelclass Student(Person):    school = "yyyy"    def __init__(self,name,age,course):        Person.__init__(self,name,age)        self.course=course    def study(self):        Person.study(self)        print("%s学生在学习"%self.name

2 与继承有关系的重用

super关键字

super在经典类和新式类使用的区别

经典类

新式类

#Python交流学习Q群:711312441class Person(object):    school = "oldboy"    def __init__(self,name,age):        self.name=name        self.age=age    def study(self):        print("study....")class Student(Person):    school = "yyyy"    def __init__(self,name,age,course):        #super() 会按照mro列表拿到父类对象        super().__init__(name,age)        # super(Student,self).__init__(name,age)        self.course=course    def study(self):        Person.study(self)        super().study()        print("%s学生在学习"%self.name)stu1=Student("wed",19,"Python")stu1.study()print(Student.__mro__)
study....study....wed学生在学习(, , )

二、重用父类两种方法的使用

1 指名道姓的使用

类名.类里的方法

2 super的使用

class A:    def f1(self):        print("A.f1")class B:    def f1(self):        print("B.f1")    def f2(self):        print("B.f2")        super().f1()        # return "xxxxx"#class C(A,B):#注意这个顺序,这个顺序报错class C(B,A):    def f1(self):        print("C.f1")                        c=C()c.f2()print(C.mro())
B.f2A.f1[, , , ]

推荐内容