在阅读OpenStack的代码时,我遇到了这个问题。
名为“Service”的类继承基类“object”,然后在Service的__init__()
方法中调用对象的__init__
。相关代码如下所示:
班级定义:
class Service(object):
和Service的init方法定义:
def __init__(self, host, binary, topic, manager, report_interval=None,
periodic_interval=None, *args, **kwargs):
在Service的init中调用super(这里的'object'):
super(Service, self).__init__(*args, **kwargs)
我不明白最后一次电话,object.__init__()
它实际上做了什么?
有人可以帮忙吗?
答案 0 :(得分:14)
简短的回答是object .__ init __()方法除了检查没有传入任何参数外什么都不做。有关详细信息,请参阅the source。
在 Service 的实例上调用时, super() 调用将委托给对象.__ 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')
在该示例中,初始化按以下顺序发生:
答案 1 :(得分:3)
super()
并不总是返回父类的代理。而是返回 MRO 中下一个类的代理。在单继承中,MRO和继承链之间没有区别。在多继承中,MRO可能会导致其他继承链上的类。
答案 2 :(得分:1)
object.__init__()
实际上并没有做任何事情,但即使某个类只有super()
作为超类,也应该包含object
调用。
'超级'的一个大问题是它听起来会导致它 superclass要调用的方法的副本。这根本不是 case,它会导致MRO中的下一个方法被调用(...)People 省略对super(...)的调用。 init 如果唯一的超类是'object', 毕竟,对象。 init 什么都不做!但是,这是 非常不正确。这样做会导致其他类的 init 方法 不被称为。