简短的答案是object .()方法不执行任何操作,只是检查是否已传入任何参数。有关详细信息,请参见源。
在 Service 实例上调用时,super() 调用将委派给object .(),并且不会发生任何事情。
但是,当调用 Service 子类的实例时,事情会变得更加有趣。该 超() 调用有可能委托给一些类以外 的对象 ,一类是实例的父但不是家长服务 。有关它如何工作以及为什么有用的详细信息,请参阅博客文章Python的“超级被认为是超级”!
下面的例子(有点做作)所示的一个子类如何 服务 可能会导致 超级 呼叫 服务 被定向到另一个名为类 颜色 :
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')
在示例中,初始化按以下顺序进行: