Let a class behave like it's a list in Python

前端 未结 4 1413
太阳男子
太阳男子 2020-12-08 18:39

I have a class which is essentially a collection/list of things. But I want to add some extra functions to this list. What I would like, is the following:

  • I h
4条回答
  •  没有蜡笔的小新
    2020-12-08 19:16

    Based on the two example methods you included in your post (fancyPrint, findAMetric), it doesn't seem that you need to store any extra state in your lists. If this is the case, you're best off simple declaring these as free functions and ignoring subtyping altogether; this completely avoids problems like list vs UserList, fragile edge cases like return types for __add__, unexpected Liskov issues, &c. Instead, you can write your functions, write your unit tests for their output, and rest assured that everything will work exactly as intended.

    As an added benefit, this means your functions will work with any iterable types (such as generator expressions) without any extra effort.

提交回复
热议问题