设为首页 加入收藏

TOP

Python重用父类方法
2023-07-25 21:29:05 】 浏览:37
Tags:Python 方法

一、重用父类方法

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

2 与继承有关系的重用

super关键字

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

经典类

  • super(Student,self).__init__(name,age)----->Student:当前子类,self:当前对象
  • python3中没有经典类,所以这种方式一般是在python2中写
  • python3中也会有这种写法,这样写是为了代码可以向下兼容,拿到python2中也可以直接使用

新式类

  • super().__init__(name,age):括号里面不加参数
  • super() 会按照__mro__列表拿到父类对象
  • 它是通过对象来调用绑定方法的,不需要传递第一个参数,对象调用父类的绑定方法时,对自动将对象自己传进去
#Python交流学习Q群:711312441
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....

study....

wed学生在学习
(<class 'main.Student'>, <class 'main.Person'>, <class 'object'>)

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

1 指名道姓的使用

类名.类里的方法

  • 一般在没有继承关系的时候使用
  • 如果继承了多个父类,super是按照mro列表找,现在想确切的用某个父类的某个方法,就需要指名道姓的使用

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'>]
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python 发起post/get请求(封装) 下一篇状态机的实现

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目