python:继承或组成 [英] python: inheriting or composition

查看:112
本文介绍了python:继承或组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有,它使用 dict 的一些功能。我曾经将一个 dict 对象复合在一起,并从外部提供一些访问权限,但最近考虑到只是继承 dict 添加一些我可能需要的属性和方法。这是一个很好的方法,还是应该坚持撰写?

解决方案

继承经常被滥用。除非你的班级意图被用作具有额外功能的通用字典,否则我会说组合是要走的路。



保存转接通话通常不够好选择继承的原因。



从设计模式书中:


组合超过类继承



理想情况下,您不必创建
新组件来实现重用。您可以通过组合
现有组件来获取所有
所需的所有
功能。但是这很少是
的情况,因为可用的
组件的集合在实践中从来不够丰富
。通过继承重用
使得可以更容易地制作新的组件
,可以使用旧的组件。
继承和对象组合
因此一起工作。



然而,我们的经验是
设计师过度使用继承作为
重用技术和设计通常是
,更多地可以使用
(更简单),更多地依赖于对象组合。


整个文字在这里:
http://blog.platinumsolutions.com/node/129


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?

解决方案

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

这篇关于python:继承或组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆