Python多重继承
跳转到导航
跳转到搜索
调用未绑定的父类方法
有个也叫 用类名调用父类
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')
'''
Parent
Child
HelloWorld from Parent
Child bar function.
I'm the parent.
'''
使用supper function
这个方法更加好
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)
super(FooChild, self).bar(message)
print 'Child bar function.'
print self.parent
if __name__ =='__main__':
foochild = FooChild()
foochild.bar('HelloWorld')
'''
Parent
Child
HelloWorld from Parent
Child bar function.
I'm the parent.
'''
知识点
从运行结果上看,普通继承和super继承是一样的。但是其实它们的内部运行机制不一样,这一点在多重继承时体现得很明显。在super机制里可以保证公共父类仅被执行一次,至于执行的顺序,是按照mro进行的(E.__mro__)。
注意super继承只能用于新式类,用于经典类时就会报错。
新式类:必须有继承的类,如果没什么想继承的,那就继承object
经典类:没有父类,如果此时调用super就会出现错误:『super() argument 1 must be type, not classobj』
注意在Python3.0里语法有所改变:你可以用super().__init__()替换super(ChildB, self).__init__() 我早上就遇到这个坑 哈哈