Overriding append method after inheriting from a Python List

前端 未结 6 1741
长情又很酷
长情又很酷 2020-11-27 17:33

I want to create a list that can only accept certain types. As such, I\'m trying to inherit from a list in Python, and overriding the append() method like so:



        
6条回答
  •  隐瞒了意图╮
    2020-11-27 18:25

    By not doing it in the first place.

    If you don't want something of type X in your list, why are you putting it there?

    This is not a sarcastic response. Adding type restrictions as you are trying is either unnecessary or affirmatively counter-productive. It is however, a common request from people coming from a language background which has strict compile-time type checking.

    For the same reason you wouldn't attempt 'a string' / 2.0, you have the same control over what gets put in a list. Since a list will happily contain heterogeneous types, at best TypedList will move a run-time TypeError from the point where you use the item forward in time to where you append it to the list. Given Python's duck-typing explicitly checking isinstance precludes later expansion of the list to contain non-type instances while providing no benefit.

    added OrderedDict information:

    Per request in comment, assuming Python 2.7 or greater collections.OrderedDict will do it. Per that documentation page, given 2.4 or greater you have to add one.

提交回复
热议问题