0
votes

I premit that I am begginer with *args and **kwargs. I was trying to make some mock code imitating what I have seen been doing in this forum and elsewhere on the net. However, when I have tried to do something similar to what I have seen, I received an unexpected error. This is the example:

class A():
    defined = []
    def __new__(cls, *args, **kwargs):
        new = kwargs['new']
        if not new and len(A.defined)>0:
            x = A.defined[0]
        else:
            # x = super().__new__(cls, *args, **kwargs)
            # if I use this, it raises error: 
            # "TypeError: object.__new__() takes exactly one argument (the type to instantiate)"
            x = super().__new__(cls)
            # this works
        return x

    def __init__(self, value, *args, **kwargs):
        self.value = value
        A.defined.append(self) 

a = A("a", new = True)

Why is there this error?

Thanks.

1
The formatting of the code is a bit off... Please edit that and include the full error output from running exactly the code you post here. Also, I wonder, are *args and **kwargs actually relevant to your question? - Ulrich Eckhardt

1 Answers

1
votes

when you use super().__new__ it is the __new__ method of object class, which takes exactly one argument (cls). since you are also forwarding to it the *args, **kwargs arguments, you are basically sending (cls, new=True) to a method that expects only (cls)

hope that makes sense