简体   繁体   中英

When I inherit from frozenset, I get TypeError: object.__init__() takes exactly one argument (the instance to initialize)

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?

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM