详解python的super()的作用和原理:
Python 中对象的定义很怪异,第一个参数一般都命名为self,
用于传递对象本本身,而在调用的时候则不必显示传递,系统会自动传递
今天我们介绍的主角是super(),在类的继承里面super()非常常用,
它解决了子类调用父类方法的一些问题,父类多次被调用只执行一次。
当存在继承关系的时候,有时候需要在子类中调用父类的方法
此时最简单的方法是把对象调用转换成类调用,需要注意的是这时
self参数需要显示传递
class FooParent:
def bar(self, message):
print(message)
class FooChild(FooParent):
def bar(self, message):
FooParent.bar(self, message)
print FooChild().bar("Hello, Python.")
这样做有一些缺点,比如说如果修改了父类名称,那么在子类中会涉及多处修改,
另外,Python是允许多继承的语言,如上所示的方法在多继承时就需要重复写多次,
显得累赘。为了解决这些问题,Python引入了super()机制,例子代码如下:
node2:/root/python/object#cat t2.py
class FooParent:
def bar(self, message):
print(message)
class FooChild(FooParent):
def bar(self, message):
super(FooChild, self).bar(message)
FooChild().bar("Hello, Python.")
node2:/root/python/object#python3 t2.py
Hello, Python.