Python 中关于多重继承的怪癖!至少我这么认为
我一直在研究与此类似的多重继承代码:
class Document():
def save(self, x):
print "inside Document from " + x
class Cdm(object):
def save(self,x):
print "inside Cdm from " + x
super(Cdm,self).save('Cdm')
class Contacts(Cdm, Document):
def __init__(self):
self.save('Contacts')
这是我创建联系人实例时得到的结果。
> c = Contacts()
< inside Cdm from Contacts
< inside Document from Cdm
现在这很奇怪,可能在我看来。我可能误会了什么。正如您所看到的,Contacts 类继承自 cdm 和 Document。我正在尝试使用联系人中 Cdm 的保存方法。但是Cdm继承自object并且没有名为save的超类方法,但它从Document类调用save函数。在我正在工作的程序中,这是我想要的行为,但我很担心,因为理论上它不应该起作用,或者至少我认为是这样。
您对此有何评论?或者我误解了Python的继承。
I have been working on a multiple inheritance code which looks similar to this:
class Document():
def save(self, x):
print "inside Document from " + x
class Cdm(object):
def save(self,x):
print "inside Cdm from " + x
super(Cdm,self).save('Cdm')
class Contacts(Cdm, Document):
def __init__(self):
self.save('Contacts')
This is the result I get when I create an instance of Contacts.
> c = Contacts()
< inside Cdm from Contacts
< inside Document from Cdm
Now this is just weird, possibly to my eye. I might have misunderstood something. As you can see, the class Contacts inherits from cdm and Document. I am trying to use the save method of Cdm from Contacts. But Cdm inherits from object and does not have a super class method called save yet it calls the save function from Document class. In the program what I am working this is the behaviour I want but I am worried as theoretically it should not work or at least I think.
Do you have any comments on this. Or have I misunderstood Python's inheritance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 Python 文档 所说:
在这种情况下,
super(Cdm,self).save('Cdm')
将调用方法解析顺序中的下一个save()
版本。在这种情况下,它是Document
类中的save()
方法,因为它是Cdm
的兄弟类(即,它是第二个基类)Contacts
类)。可以在这里找到
super()
的实用解释:Python 的 super() 被认为是 super!As Python documentation says:
In that situation,
super(Cdm,self).save('Cdm')
will call the version ofsave()
which is next in method resolution order. In that case it is thesave()
method in theDocument
class because it is a sibling class ofCdm
(i.e. it is the second base class ofContacts
).A great practical explanation of
super()
can be found here: Python’s super() considered super!super(Cdm,self).save('Cdm')
调用 mro 中下一个类的save
方法。这可能不是当前类的直接父类。有关 super 的工作原理和用途的更多信息,您可以参考 文档 和这篇博文。
super(Cdm,self).save('Cdm')
calls thesave
method of the next class in the mro. This may not be a direct parent of the current class.For more info about how super works and what it can be used for, you can refer to the documentation and this blog post.