Subclass Python list to Validate New Items

后端 未结 6 1402
广开言路
广开言路 2021-01-13 14:46

I want a python list which represents itself externally as an average of its internal list items, but otherwise behaves as a list. It should raise a TypeError i

6条回答
  •  星月不相逢
    2021-01-13 15:35

    Inherit from MutableSequence and implement the methods it requires as well as any others that fall outside of the scope of Sequences alone -- like the operators here. This will allow you to change the operator manipulations for list-like capabilities while automatically generating iterators and contains capabilities.

    If you want to check for slices btw you need to do isinstance(key, slice) in your __getitem__ (and/or __setitem__) methods. Note that a single index like myList[0] is not a slice request, but a single index and myList[:0] is an actual slice request.

提交回复
热议问题