1

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
  • 2
    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? Commented May 17, 2020 at 7:35

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.