python 类中 super ()方法的使用

python 类中 super ()方法的使用
super() 是pyhton 中调用父类(超类)的一种方法,在子类中可以通过super()方法来调用父类的方法:
超类: 是指 2层以上的继承关系,假如 C类继承B类,B类由继承A类,那么A类就是C类的超类~
1 通过super() 来调用父类的__init__ 构造方法:
class Person():
      def __init__(self):
        print('我是Peson的__init__构造方法')

class Student(Person):
        def __init__(self):
         super().__init__()
          print('我是Student的__init__构造方法')

stu = Student()
  
-----------------------------------------
我是Peson的__init__构造方法
我是Student的__init__构造方法

2 通过supper() 来调用与子类同名的父类方法

class Person():
      def say(self):
       print('我是Peson的say方法')

class Student(Person):
        def say(self):
        super().say()
        print('我是Student的的say方法')

stu = Student()
stu.say()
-----------------------------------------
'我是Peson的say方法'
'我是Student的的say方法'

3 通过super()调用超类的同名方法

class Person():
      def say(self):
       print('我是Peson的say方法')

class Student(Person):
        def __init__(self):
        print('我是Student的__init__构造方法')

class Xiaoming(Student):
        def say(self):
             super().say()
       print('我是Xiaoming的say方法')

Xiao= Xiaoming()
Xiao.say()
------------------------------------
'我是Student的__init__构造方法'
'我是Peson的say方法'
 我是Xiaoming的say方法

注意:因为Xiaoming 没有__init__ 构造方法,实例化的时候会执行父类Student的__init__构造方法,所以先打印我是Student的__init__构造方法.super().say()因为Xiaoming 的父类Student 没有say()方法,就执行了其超类Person的say()方法,如果Student 有say方法则执行Student的say 方法
    比如:

class Person():
      def say(self):
       print('我是Peson的say方法')

class Student(Person):
        def __init__(self):
        print('我是Student的__init__构造方法')
        def say(self):
       print('我是Student的say方法')


class Xiaoming(Student):
        def say(self):
             super().say()
       print('我是Xiaoming的say方法')

Xiao= Xiaoming()
Xiao.say()
--------------------------

'我是Student的__init__构造方法'
'我是Student的say方法'
 我是Xiaoming的say方法
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值