Python中super的用法实例

yipeiwu_com5年前Python基础

super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。总之前人留下的经验就是:保持一致性。要不全部用类名调用父类,要不就全部用 super,不要一半一半。

普通继承

复制代码 代码如下:

class FooParent(object): 
    def __init__(self): 
        self.parent = 'I\'m the parent.' 
        print 'Parent' 
     
    def bar(self,message): 
        print message, 'from Parent' 
         
class FooChild(FooParent): 
    def __init__(self): 
        FooParent.__init__(self) 
        print 'Child' 
         
    def bar(self,message): 
        FooParent.bar(self,message) 
        print 'Child bar function.' 
        print self.parent 
         
if __name__=='__main__': 
    fooChild = FooChild() 
    fooChild.bar('HelloWorld') 

super继承

复制代码 代码如下:

class FooParent(object): 
    def __init__(self): 
        self.parent = 'I\'m the parent.' 
        print 'Parent' 
     
    def bar(self,message): 
        print message,'from Parent' 
 
class FooChild(FooParent): 
    def __init__(self): 
        super(FooChild,self).__init__() 
        print 'Child' 
         
    def bar(self,message): 
        super(FooChild, self).bar(message) 
        print 'Child bar fuction' 
        print self.parent 
 
if __name__ == '__main__': 
    fooChild = FooChild() 
    fooChild.bar('HelloWorld') 

程序运行结果相同,为:

复制代码 代码如下:

Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.

从运行结果上看,普通继承和super继承是一样的。但是其实它们的内部运行机制不一样,这一点在多重继承时体现得很明显。在super机制里可以保证公共父类仅被执行一次,至于执行的顺序,是按照mro进行的(E.__mro__)。
注意super继承只能用于新式类,用于经典类时就会报错。
新式类:必须有继承的类,如果没什么想继承的,那就继承object
经典类:没有父类,如果此时调用super就会出现错误:『super() argument 1 must be type, not classobj』

关于super用法的详细研究可参考「/post/66912.htm

相关文章

Python利用matplotlib绘制约数个数统计图示例

Python利用matplotlib绘制约数个数统计图示例

本文实例讲述了Python利用matplotlib绘制约数个数统计图。分享给大家供大家参考,具体如下: 利用Python计算1000以内自然数的约数个数,然后通过matplotlib绘制...

使用grappelli为django admin后台添加模板

grappelli是github上面star最多的django模板系统 http://django-grappelli.readthedocs.org/en/latest/quickst...

Django缓存系统实现过程解析

在动态网站中,用户每次请求一个页面,服务器都会执行以下操作:查询数据库,渲染模板,执行业务逻辑,最后生成用户可查看的页面。 这会消耗大量的资源,当访问用户量非常大时,就要考虑这个问题了。...

Django组件content-type使用方法详解

Django组件content-type使用方法详解

前言 一个表和多个表进行关联,但具体随着业务的加深,表不断的增加,关联的数量不断的增加,怎么通过一开始通过表的设计后,不在后期在修改表,彻底的解决这个问题呢呢 django中的一个组件c...

Pycharm无法使用已经安装Selenium的解决方法

Pycharm无法使用已经安装Selenium的解决方法

电脑C盘安装python27的时候也安装了selenium,但是最近刚刚使用工具Pycharm,新建工程后,然后建立.py文件后,使用语句:from selenium.webdriver...