Subclass Python list to Validate New Items

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

    There are 7 methods of the list class that add elements to the list and would have to be checked. Here's one compact implementation:

    def check_float(x):
        try:
            f = float(x)
        except:
            raise TypeError("Cannot add %s to AverageList" % str(x))
    
    def modify_method(f, which_arg=0, takes_list=False):
        def new_f(*args):
            if takes_list:
                map(check_float, args[which_arg + 1])
            else:
                check_float(args[which_arg + 1])
            return f(*args)
        return new_f
    
    class AverageList(list):
        def __check_float(self, x):
            try:
                f = float(x)
            except:
                raise TypeError("Cannot add %s to AverageList" % str(x))
    
        append = modify_method(list.append)
        extend = modify_method(list.extend, takes_list=True)
        insert = modify_method(list.insert, 1)
        __add__ = modify_method(list.__add__, takes_list=True)
        __iadd__ = modify_method(list.__iadd__, takes_list=True)
        __setitem__ = modify_method(list.__setitem__, 1)
        __setslice__ = modify_method(list.__setslice__, 2, takes_list=True)
    

提交回复
热议问题