简短的回答是 object.__init__() 方法除了检查是否没有传入任何参数之外什么都不做。有关详细信息,请参阅the source。
当在 Service 的实例上调用时,super() 调用将委托给 object.__init__() 并且不会发生任何事情。
然而,当调用 Service 的子类的实例时,事情会变得更有趣。 super() 调用可以潜在地委托给 object 以外的某个类,该类是实例的父类,但不是 Service的父类>。有关其工作原理以及为何有用的详细信息,请参阅博客文章 Python's Super Considered Super!
下面的例子(有点做作)展示了 Service 的子类如何导致 Service 中的 super 调用被定向到另一个类称为颜色:
class Service(object):
def __init__(self, host, binary, topic, manager, report_interval=None,
periodic_interval=None, *args, **kwargs):
print 'Initializing Service'
super(Service, self).__init__(*args, **kwargs)
class Color(object):
def __init__(self, color='red', **kwargs):
print 'Initializing Color'
self.color = color
super(Color, self).__init__(**kwargs)
class ColoredService(Service, Color):
def __init__(self, *args, **kwds):
print 'Initializing Colored Service'
super(ColoredService, self).__init__(*args, **kwds)
c = ColoredService('host', 'bin', 'top', 'mgr', 'ivl', color='blue')
在示例中,初始化按以下顺序进行:
- 初始化彩色服务
- 初始化服务
- 初始化颜色
- 初始化对象——除了参数检查什么都不做