How to subclass Python list without type problems?

前端 未结 3 1290
长情又很酷
长情又很酷 2020-12-02 22:49

I want to implement a custom list class in Python as a subclass of list. What is the minimal set of methods I need to override from the base list c

相关标签:
3条回答
  • 2020-12-02 23:16

    You should probably read these two sections from the documentation:

    • Emulating container types
    • Additional methods for emulating sequence types (Python 2 only)

    Edit: In order to handle extended slicing, you should make your __getitem__-method handle slice-objects (see here, a little further down).

    0 讨论(0)
  • 2020-12-02 23:26

    Firstly, I recommend you follow Björn Pollex's advice (+1).

    To get past this particular problem (type(l2 + l3) == CustomList), you need to implement a custom __add__():

       def __add__(self, rhs):
            return CustomList(list.__add__(self, rhs))
    

    And for extended slicing:

        def __getitem__(self, item):
            result = list.__getitem__(self, item)
            try:
                return CustomList(result)
            except TypeError:
                return result
    

    I also recommend...

    pydoc list
    

    ...at your command prompt. You'll see which methods list exposes and this will give you a good indication as to which ones you need to override.

    0 讨论(0)
  • 2020-12-02 23:32

    Possible cut-the-gordian-knot solution: subclass UserList instead of list. (Worked for me.) That is what UserList is there for.

    0 讨论(0)
提交回复
热议问题