Subclass Python list to Validate New Items

后端 未结 6 1460
广开言路
广开言路 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:24

    The array.array class will take care of the float part:

    class AverageList(array.array):
        def __new__(cls, *args, **kw):
            return array.array.__new__(cls, 'd')
        def __init__(self, values=()):
            self.extend(values)
        def __repr__(self):
            if not len(self): return 'Empty'
            return repr(math.fsum(self)/len(self))
    

    And some tests:

    >>> s = AverageList([1,2])
    >>> s
    1.5
    >>> s.append(9)
    >>> s
    4.0
    >>> s.extend('lol')
    Traceback (most recent call last):
      File "", line 1, in 
        s.extend('lol')
    TypeError: a float is required
    

提交回复
热议问题