首页 > 技术文章 > [修]python普通继承方式和super继承方式

spaceship9 2013-12-02 21:52 原文

[转]python普通继承方式和super继承方式

 

原文出自:http://www.360doc.com/content/13/0306/15/9934052_269664772.shtml

原文的错误,已经被我修改掉了。

 

 

 

普通继承:

class FooParent(object):
    def __init__(self):
        self.parent='Im 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

结果:

>>> fooChild = FooChild()
Parent
Child
>>> fooChild.bar("Hello World")
Hello World from Parent
Child bar function.
Im the parent.

 

 
 
==========================================================
super继承:
新建一个bo.py的文件
 
下面上代码,方便未来人调试。
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__()  #意思跟上面差不多,只是这里直接调用的super寻找父辈函数,然后用了super的__init__()
        print 'Child'
# 这一点在多重继承时体现得很明显。在super机制里可以保证公共父类仅被执行一次,至于执行的顺序,是按照mro进行的(E.__mro__)。
    def bar(self, message):
        super(FooChild, self).bar(message)
        print 'Child bar function. '
        print self.parent

开始检验结果:


    fooChild = FooChild()
    fooChild.bar("HelloWorld")

 从上面看起来,似乎结果是一样的。

 
================================================================================
从运行结果上来看普通继承跟super继承是一样的,但是其实它们的内部运行机制不太一样,这一点在多重继承时体现得很明显。在super机制里可以保证公共父类仅被执行一次,至于执行的顺序,是按照mro进行的(E.__mro__)。http://hi.baidu.com/thinkinginlamp/item/3095e2f52c642516ce9f32d5
 
注意super继承只能用于新式类,用于经典类时就会报错。
新式类:必须有继承的类,如果没什么想继承的,那就继承objcet
经典类:没有父类,如果此时调用super就会出现错误:“super() argument 1 must be type, not classobj
 
 这里我们把更多的内容加入到这个里面去:采用的是上面的那个链接 http://hi.baidu.com/thinkinginlamp/item/3095e2f52c642516ce9f32d5这个一定要读一下,代码并不是很难,
给出的实例很科学的。赞赏一个。为了避免公共父类被执行多次,就采用了super(child, self).__init__() 

如何在Python中调用父类的同名方法

 
 
 
 
 
 

 

推荐阅读