python:继承或组合
假设我有 class
,它使用 dict
的一些功能。我曾经在内部组合一个 dict 对象并提供一些来自外部的访问,但最近考虑简单地继承 dict 并添加一些我可能需要的属性和方法。这是一个好方法,还是我应该坚持构图?
Let's say that I have class
, that uses some functionality of dict
. I used to composite a dict
object inside and provide some access from the outside, but recently thought about simply inheriting dict
and adding some attributes and methods that I might require. Is it a good way to go, or should I stick to composition?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
继承经常被滥用。除非您的类旨在用作具有额外功能的通用字典,否则我认为组合是可行的方法。
保存转发调用通常并不是选择继承的充分理由。
来自《设计模式》一书:
全文如下:
http://blog.platinumsolutions.com/node/129
Inheritance is very often abused. Unless your class is meant to be used as a generic dictionary with extra functionality, I would say composition is the way to go.
Saving forwarding calls is usually not a good enough reason for choosing inheritance.
From the Design Pattern book:
The entire text is here:
http://blog.platinumsolutions.com/node/129
您确实必须权衡您要做的事情的成本和范围。从
dict
继承,因为您想要类似字典的行为,既快速又简单,但容易受到限制,例如导致从您的类创建的对象不可散列。例如,如果您需要序列化(即
pickle
)对象,但也想要类似字典的行为,那么显然您不能直接从dict
并且您需要组合您想要实现的功能的各个部分。You really have to weigh out the cost and scope of what you're trying to do. Inheriting from
dict
because you want dictionary-like behavior is quick and easy but prone to limitations such as causing objects created from your class to be unhashable.So for example, if you are going to need to serialize (i.e.
pickle
) the objects, but also want dictionary-like behavior, then obviously you can't inherit directly fromdict
and you'll need to compose the parts of the functionality you desire to make that happen.isinstance(my_object, dict) 应该返回 True 还是 False?换句话说,如果您不小心将其中一个对象提供给需要
dict
的对象,它是否应该愉快地尝试将其用作dict
?可能不会,所以使用组合。Should
isinstance(my_object, dict)
return True or False? In other words, if you accidentally give one of the objects to something that wants adict
, should it blithely try to use it as adict
? Probably not, so use composition.两者都很好,但我更喜欢继承,因为这意味着更少的代码(只要可读就总是好的)。
Dive into Python 有一个非常相关的示例。
在 Python 2.2 及更早版本中,您无法直接从内置函数派生子类,因此您必须使用组合。
Both are good, but I'd prefer inheriting, as it will mean less code (which is always good as long as it is readable).
Dive into Python has a very relevant example.
On Python 2.2 and prior, you couldn't subclass from built ins directly, so you had to use composition.