086 重用父類方法

1、重用父類方法

1.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=level

class 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)

1.2 與繼承有關係的重用

  • super關鍵字

1.2.1 super在經典類和新式類使用的區別

  • 經典類
    • super(Student,self).__init__(name,age)----->Student:當前子類,self:當前對象
    • python3中沒有經典類,因此這種方式通常是在python2中寫
    • python3中也會有這種寫法,這樣寫是爲了代碼能夠向下兼容,拿到python2中也能夠直接使用
  • 新式類
    • super().__init__(name,age):括號裏面不加參數
    • super() 會按照__mro__列表拿到父類對象
    • 它是經過對象來調用綁定方法的,不須要傳遞第一個參數,對象調用父類的綁定方法時,對自動將對象本身傳進去
class 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....python

study....學習

wed學生在學習
(<class 'main.Student'>, <class 'main.Person'>, <class 'object'>)code

2、重用父類兩種方法的使用

2.1 指名道姓的使用

  • 類名.類裏的方法
    • 通常在沒有繼承關係的時候使用
    • 若是繼承了多個父類,super是按照mro列表找,如今想確切的用某個父類的某個方法,就須要指名道姓的使用

2.2 super的使用

  • super().方法名()
  • 有繼承關係的時候使用
  • super()至關於獲得了一個特殊對象,第一個參數不須要傳,調用綁定方法,會把本身傳過去
  • 使用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()
        # return 'xxxxx'

#class C(A,B):
#注意這個順序,這個順序報錯
class C(B,A):
    def f1(self):
        print('C.f1')
        
        
        
c=C()
c.f2()
print(C.mro())

B.f2
A.f1對象

[<class 'main.C'>, <class 'main.B'>, <class 'main.A'>, <class 'object'>]繼承

相關文章
相關標籤/搜索