python中多重继承,用super()函数的示例详解

1、复杂的继承,super 函数会大大提高代码的可控性。

2、示例描述。

创建相对复杂的继承关系类结构:
(1)创建一个父类,派生出两个子类,每个子类都需要调用父类的方法。
(2)创建一个孙子类,继承这两个子类。孙子类也需要调用其每个父类的方法。

3、反面案例:直接调用父类,实现多重继承中的父类调用。

class Record:
    __Occupation = 'scientist'

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def show_record(self):
        print('occupation:', self.get_occupation())

    def get_occupation(self):
        return self.__Occupation


class FemaleRecord(Record):
    def show_record(self):
        print(self.name, ':', self.age, ',female')
        Record.show_record(self)


class RetireRecord(Record):
    def show_record(self):
        Record.show_record(self)
        print('retired worker')


class ThisRecord(FemaleRecord, RetireRecord):
    def show_record(self):
        print('the member detail as follow:')
        FemaleRecord.show_record(self)
        RetireRecord.show_record(self)


myc = ThisRecord('Anna', 62)
myc.show_record()
最后两行是对孙子类 ThisRecord 的实例化,并调用其实例化的 showrecode 函数。
代码运行后,输出如下:
the member detail as follow:
Anna : 62 ,female
Occupation: scientist
Occupation: scientist
retired worker
 
在实际编程过程中,这种父类函数被自动执行多次的情况是一定要避免的。如果 showrecode
函数中做了一些资源申请之类的操作,这种写法会导致资源泄漏,会严重地影响程序的性能。
而且,代码中并没有调用两次的语句,这也大大增加了排查错误的困难。接下来,就使用 super
函数对该例子进行优化,避免这种情况的发生。

4、正确案例:使用 super 函数,实现多重继承中的父类调用。

class Record:
    __Occupation = 'scientist'

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def show_record(self):
        print('occupation:', self.get_occupation())

    def get_occupation(self):
        return self.__Occupation


class FemaleRecord(Record):
    def show_record(self):
        print(self.name, ':', self.age, ',female')
        super().show_record()


class RetireRecord(Record):
    def show_record(self):
        super().show_record()
        print('retired worker')


class ThisRecord(FemaleRecord, RetireRecord):
    def show_record(self):
        print('the member detail as follow:')
        super().show_record()


myc = ThisRecord('Anna', 62)
myc.show_record()
代码运行后,输出如下:
the member detail as follow:
Anna : 62 ,female
Occupation: scientist
retired worker
 
“Occupation: scientist”只输出了一次。表明父类 Record 中 的 showrecode 函数被调用了一遍,程序达到了想要的效果。另外,在孙子类的函数 showrecode 中,使用 super 函数返回的是其继承的多个父类列表。系统会按照继承时的顺序,依次对每个 父类进行 showrecode 方法的调用。
 

5、总结

super 函数,是 Python 面向对象部分内置的一个非常有用的函数,它能提高程序的稳
定性、可控性,也使得代码更为简洁。尤其在处理复杂继承关系中,一定要将
super 函数应用起来。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_64880493_江哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值