Search code examples
pythonclassinheritanceconstructorfrozenset

Why this class constructor raises this error?


Having this class:

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

Executing A(range(2)) results in the following error:

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

Meanwhile, frozenset(range(2)) works, and if I inherit A from set instead, A(range(2)) also works.

If I pass to A's constructor 0 or more than 1 parameter, it works as it should (with 0 paramemeters creates an empty set, with 2 or more parameters raises TypeError: A expected at most 1 arguments, got 2).


Solution

  • Actually you need to override __new__ method (not __init__, __init__ method will accept an instance generated and returned by __new__ method) when subclassing frozenset to create a new frozenset from a passed iterable (as argument):

    class A(frozenset):
        def __new__(cls, *args):
            self = super().__new__(cls, *args)
            return self
    
    
    print(A(range(2)))
    print(A(range(2)).__class__.__bases__)
    

    Sample output:

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