Overriding append method after inheriting from a Python List

前端 未结 6 1746
长情又很酷
长情又很酷 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:26

    You can also use build-in array class. It works only with numeric types, but is probably best solution for such cases. It is optimized to minimize memory usage.

    Example:

    from array import array
    array('c', 'hello world')     # char array
    array('u', u'hello \u2641')   # unicode array
    array('l', [1, 2, 3, 4, 5])   # long array
    array('d', [1.0, 2.0, 3.14])  # double array
    

    You can perform the same operations as with normal list:

    chars = array('c')            
    chars.extend('foo')
    

    But when you try to insert other type then specified, an exception is raised:

    >>> chars.extend([5,10])
    Traceback (most recent call last):
       File "", line 1, in 
    TypeError: array item must be char  
    

    For all available types look here

提交回复
热议问题