What to consider before subclassing list?

后端 未结 4 1231
闹比i
闹比i 2020-12-03 17:04

I was recently going over a coding problem I was having and someone looking at the code said that subclassing list was bad (my problem was unrelated to that class). He said

4条回答
  •  攒了一身酷
    2020-12-03 17:56

    The abstract base classes provided in the collections module, particularly MutableSequence, can be useful when implementing list-like classes. These are available in Python 2.6 and later.

    With ABCs you can implement the "core" functionality of your class and it will provide the methods which logically depend on what you've defined.

    For example, implementing __getitem__ in a collections.Sequence-derived class will be enough to provide your class with __contains__, __iter__, and other methods.

    You may still want to use a contained list object to do the heavy lifting.

提交回复
热议问题