Python学习笔记 --- 学会super用法

其实很多人对于Python中的super理解并没有很明白,其中主要是对于使用。这里简单的讲解一下。

当存在继承关系的时候,有时候需要在子类中调用父类的方法,此时最简单的方法是把对象调用转换成类调用,需要注意的是这时self参数需要显式传递

 

例如:

 

 

>>> class FooParent:
def bar(self, message):
print(message)

>>> class FooChild(FooParent):
def bar(self, message):
FooParent.bar(self, message)

>>> FooChild().bar("Hello, World.")
Hello, World.

 

 

这里懂了的话,继续:

这样做有一些缺点,比如说如果修改了父类名称,那么在子类中会涉及多处修改,另外,python是允许多继承的语言,如上所示的方法在多继承时就需要重复写多次,显得累赘。为了解决这些问题,Python引入了super()机制,例子代码如下:

 

 

 

class FooParent(object):
    def bar(self, message):
        print message
class FooChild(FooParent):
    def bar(self, message):
        super(FooChild, self).bar(message)

FooChild().bar("Hello, World")

 

 

 

最后总结来说,super的引用是为了减少代码的的修改导致的错误,以及大量的重复修改的工作。

posted @ 2017-07-26 10:27  天涯海角路  阅读(145)  评论(0)    收藏  举报