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

前端 未结 4 1408
太阳男子
太阳男子 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:08

    The simplest solution here is to inherit from list class:

    class MyFancyList(list):
        def fancyFunc(self):
            # do something fancy
    

    You can then use MyFancyList type as a list, and use its specific methods.

    Inheritance introduces a strong coupling between your object and list. The approach you implement is basically a proxy object. The way to use heavily depends of the way you will use the object. If it have to be a list, then inheritance is probably a good choice.


    EDIT: as pointed out by @acdr, some methods returning list copy should be overriden in order to return a MyFancyList instead a list.

    A simple way to implement that:

    class MyFancyList(list):
        def fancyFunc(self):
            # do something fancy
        def __add__(self, *args, **kwargs):
            return MyFancyList(super().__add__(*args, **kwargs))
    

提交回复
热议问题