089 重用父类方法的两种方式

重用父类方法有两种方式:

  1. 指名道姓的使用,直接调用指定类的方法
  2. super关键字使用

一、直接调用指定类的方法

  • 指名道姓的使用,跟继承没有关系。但也能完成需求
class Person:
    school = 'xxx'
    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):
        # 直接调用Person类的__init__方法
        Person.__init__(self,name,age)
        self.course=course
    def study(self):
        Person.study(self)
        print("%s学生在学习"%self.name)
        
stu1=Student('wed',19,"Python")
# stu1.school='xxx'
print(stu1.school)
stu1.study()

yyyy
study....
wed学生在学习

二、通过super()关键字

首先,super()是用来调用父类(超类)的一个方法

它的调用顺序是根据 对象的mro()方法中的调用顺序来进行调用的

2.1 使用方法

super()的使用方法,在python2和python3中并不相同。

  • 新式类的写法:

    super().__init__(参数1,参数2) # 新式类,调用父类的init方法并传参
  • 经典类的写法:

    super(当前类名,self).__init__(参数1,参数2) # 经典类,调用父类的init方法并传参

2.2 使用super调用父类方法

class Person(object):
    school = 'xxx'
    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列表拿到父类对象
        #对象来调用绑定方法,不需要传递第一个参数(self)
        super().__init__(name,age)
        #经典类和新式类
        #经典类中必须这么写(py3中没有经典类),都用上面那种方式写
        # 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.school='xxx'
# print(stu1.school)
stu1.study()

2.3 super()的调用顺序

牢记:它的调用顺序是根据 对象的mro()方法中的调用顺序来进行调用的

# super是按照mro列表找
class A:
    def f1(self):
        print('A.f1')
class B:
    def f1(self):
        print('B.f1')
    def f2(self):
        print('B.f2')

        # 重点
        super().f1()


class C(B,A):
#注意这个顺序,这个顺序报错
# class C(A,B):
    def f1(self):
        print('C.f1')

#C实例化产生一个对象
c=C()
# print(c.f2())
print(C.mro())
c.f2()

[<class 'main.C'>, <class 'main.B'>, <class 'main.A'>, <class 'object'>]
B.f2
A.f1

猜你喜欢

转载自www.cnblogs.com/XuChengNotes/p/11419215.html
今日推荐