python中,如果存在多继承,例如
class Song(object):
"""docstring for Song"""
def __init__(self, author):
super(Song, self).__init__(author)
self._author = author
class Singer(object):
"""docstring for Singer"""
def __init__(self, name):
super(Singer, self).__init__(name)
self._name = name
class Mtv(Song, Singer):
"""docstring for RockSong"""
def __init__(self, name, author):
super(RockSong, self).__init__(name)
Mtv继承song与singer,在init方法里,如何是的两个父类进行初始化,并且完成属性赋值?
使用
super()
的辦法:Song
跟Singer
不必呼叫super
super(type, obj_or_type)
會按照 MRO 的順序去委託type
的 父類 或 兄弟類 的方法來調用super().__init__(author)
會找到<class '__main__.Song'>
並調用其__init__(author)
super(Song, self).__init__(name)
會找到<class '__main__.Singer'>
並調用其__init__(name)
結果:
P.S. 如果你是使用 Python3, 那一般的 class 不必繼承
object
這篇講的很棒, 完全理解 super: 理解 Python super
直接補上文章中的精華:
super 及他的兩個參數在做甚麼:
MRO 的順序
我回答過的問題: Python-QA