python:继承或组合

发布于 2024-08-23 19:44:48 字数 141 浏览 4 评论 0原文

假设我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

撑一把青伞 2024-08-30 19:44:48

继承经常被滥用。除非您的类旨在用作具有额外功能的通用字典,否则我认为组合是可行的方法。

保存转发调用通常并不是选择继承的充分理由。

来自《设计模式》一书:

优先考虑对象组合而不是类继承

理想情况下你不必创建
新组件实现重用。你
应该能够得到所有的
通过组装您需要的功能
通过对象现有组件
作品。但这很少是
情况下,因为可用的集合
组件永远不够丰富
在实践中。通过继承重用
使制造新组件变得更容易
可以与旧的组成。
继承和对象组合
从而共同努力。

尽管如此,我们的经验是
设计者过度使用继承作为
重用技术和设计通常
通过以下方式变得更加可重用(并且更简单)
更多地取决于对象组合。”

全文如下:
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:

Favor object composition over class inheritance

Ideally you shouldn't have to create
new components to achieve reuse. You
should be able to get all the
functionality you need by assembling
existing components through object
composition. But this is rarely the
case, because the set of available
components is never quite rich enough
in practice. Reuse by inheritance
makes it easier to make new components
that can be composed with old ones.
Inheritance and object composition
thus work together.

Nevertheless, our experience is that
designers overuse inheritance as a
reuse technique and designs are often
made more reusable (and simpler) by
depending more on object composition."

The entire text is here:
http://blog.platinumsolutions.com/node/129

桃酥萝莉 2024-08-30 19:44:48

您确实必须权衡您要做的事情的成本和范围。从 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 from dict and you'll need to compose the parts of the functionality you desire to make that happen.

感情旳空白 2024-08-30 19:44:48

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 a dict, should it blithely try to use it as a dict? Probably not, so use composition.

乙白 2024-08-30 19:44:48

两者都很好,但我更喜欢继承,因为这意味着更少的代码(只要可读就总是好的)。

Dive into Python 有一个非常相关的示例

在 Python 2.2 及更早版本中,您无法直接从内置函数派生子类,因此您必须使用组合。

类 FileInfo(dict):                  
   “存储文件元数据”
   def __init__(self, 文件名=无): 
       self["名称"] = 文件名
  1. 第一个区别是您不需要导入 UserDict 模块,因为 dict 是内置数据类型并且始终可用。第二个是您直接从 dict 继承,而不是从 UserDict.UserDict 继承。
  2. 第三个区别很微妙但很重要。 由于 UserDict 内部的工作方式,它需要您手动调用其 __init__ 方法来正确初始化其内部数据结构dict 不是这样工作的;它不是包装器,并且它不需要显式初始化

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.

class FileInfo(dict):                  
   "store file metadata"
   def __init__(self, filename=None): 
       self["name"] = filename
  1. The first difference is that you don't need to import the UserDict module, since dict is a built-in datatype and is always available. The second is that you are inheriting from dict directly, instead of from UserDict.UserDict.
  2. The third difference is subtle but important. Because of the way UserDict works internally, it requires you to manually call its __init__ method to properly initialize its internal data structures. dict does not work like this; it is not a wrapper, and it requires no explicit initialization.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文