pythonpython-2.7frozenset

In python, frozenset's subclass's __init__ method throw TypeError of arguments number


The class's __init__ method has 3 arguments, but when I instantiate it with 3 arguments, it throw an error that it expected 1 arguments. I cannot undrestand.

class ArrObj(frozenset):
    def __init__(self, elem_list, elem_count, self_count):
        super(ArrObj, self).__init__(elem_list)  # Enums, ArrObj, race_id
        self.elem_count = elem_count
        self.self_count = self_count
        assert self_count > 0


if __name__ == '__main__':
    a = ArrObj(['a', 'b', 'c'], {'a':1, 'b':2, 'c':3}, 8)
Traceback (most recent call last):
  File "G:/pycharm-projects/new_keyinfo/verify_treekeys.py", line 34, in <module>
    a = ArrObj(['a', 'b', 'c'], {'a':1, 'b':2, 'c':3}, 8)
TypeError: ArrObj expected at most 1 arguments, got 3

Solution

  • frozenset.__init__ doesn't take additional arguments, because you can't modify a frozenset after it has been created. (In fact, frozenset doesn't define __init__ at all; it just uses the __init__ it inherits from object.) The iterable you pass to frozenset is consumed by frozenset.__new__ instead.

    class ArrObj(frozenset):
        def __new__(cls, elem_list, elem_count, self_count):
            # May as well assert this before you do any more work
            assert self_count > 0
    
            obj = super().__new__(cls, elem_list)
            obj.elem_count = elem_count
            obj.self_count = self_count
            return obj