Home > Mobile >  When I inherit from frozenset, I get TypeError: object.__init__() takes exactly one argument (the in
When I inherit from frozenset, I get TypeError: object.__init__() takes exactly one argument (the in

Time:07-01

I want to inherit from frozenset and change the constructor. What I actually want to do is to make a singleton fronzeset, but instead here I'll provide a simplified example:

class B(frozenset):
    def __init__(self):
        super().__init__([1, 2, 3])

However, when I try to create an instance of B, I get an error:

B()  # TypeError: object.__init__() takes exactly one argument (the instance to initialize)

What's going on and how to fix this?

CodePudding user response:

For technical reasons, for immutable types like frozenset and tuple, etc. overriding their __init__ to set an initial value is the wrong way to go. This is partly to do with the fact that for the object to be created it has to know how large it's going to be based on the input argument.

You need to override __new__ instead. For example:

>>> class myset(frozenset):
...     def __new__(cls):
...         return super(myset, cls).__new__(cls, [1, 2, 3])
...     
...     
>>> myset()
myset([1, 2, 3])
  • Related