为什么此 class 构造函数会引发此错误?

Why this class constructor raises this error?

有这个class:

class A(frozenset):
    def __init__(self, *args):
        frozenset.__init__(self, *args)

执行 A(range(2)) 导致以下错误:

Traceback (most recent call last):
  File "<pyshell#65>", line 1, in <module>
    A(range(2))
  File "<pyshell#60>", line 3, in __init__
    frozenset.__init__(self, *args)
TypeError: object.__init__() takes no parameters

与此同时,frozenset(range(2)) 有效,如果我从 set 继承 A,则 A(range(2)) 也有效。

如果我向 A 的构造函数传递 0 个或超过 1 个参数,它会按预期工作(0 个参数创建一个空集,2 个或更多参数引发 TypeError: A expected at most 1 arguments, got 2)。

实际上你需要重写__new__方法(不是__init____init__方法将接受由__new__方法生成并返回的实例)子类化[=16] =] 从传递的可迭代对象(作为参数)创建一个新的 frozenset

class A(frozenset):
    def __new__(cls, *args):
        self = super().__new__(cls, *args)
        return self


print(A(range(2)))
print(A(range(2)).__class__.__bases__)

示例输出:

A({0, 1})
(<class 'frozenset'>,)