在python中,Frozenset的子类的__init__方法抛出参数数字的TypeError

时间:2019-10-15 14:21:36

标签: python python-2.7 frozenset

该类的__init__方法有3个参数,但是当我用3个参数实例化它时,它抛出一个错误,它期望有1个参数。我无法理解。

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

1 个答案:

答案 0 :(得分:1)

frozenset.__init__不需要其他参数,因为创建frozenset后无法对其进行修改。 (实际上,frozenset根本没有定义__init__;它仅使用从__init__继承的object。)将迭代传递给frozensetfrozenset.__new__消耗。

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