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 函数应用起来。