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
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
- 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.
- 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.