python: inheriting or composition

后端 未结 4 1252
夕颜
夕颜 2021-02-05 13:40

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

4条回答
  •  悲哀的现实
    2021-02-05 14:04

    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.

提交回复
热议问题