table of Contents
Reuse the parent class method in two ways:
- Use naming names directly call the method specified class
- super keyword
A direct call method specified class
- Use naming names, and nothing to do with inheritance. But it needs to complete
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 students in learning
Second, through the super () keyword
First of all, super () method is used to call a parent class (super class)
Its calling sequence is according to the calling object mro call sequence () method .
2.1 Use
super () method is used, and in python2 python3 are not the same.
The new class of writing:
super().__init__(参数1,参数2) # 新式类,调用父类的init方法并传参
Classic wording:
super(当前类名,self).__init__(参数1,参数2) # 经典类,调用父类的init方法并传参
2.2 use super to call the parent class method
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 () call to order
Keep in mind: it is a sequence of calls to call the calling sequence of objects mro () method .
# 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