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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
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.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.
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
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.