[Python] __new__ function behaves differently after overriding it with setattr

Discussão em 'Python' iniciado por Stack, Agosto 30, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following:

    class A:
    def __init__(self, x):
    self.x = x

    A(5) # Works fine
    x = A.__new__ # Save the function
    A.__new__ = lambda y: y # Temporarily override it
    A.__new__ = x # Restore the function
    A(5) # RAISES AN EXCEPTION!


    The last call raises an exception:

    TypeError: object.__new__() takes exactly one argument (the type to instantiate)


    What happens here?

    I'll add that x, prior to the override, was being called just fine as a __new__ function. But after the override (and the restore), it lost its ability to accept any number of arguments (*args, **kwargs).

    Continue reading...

Compartilhe esta Página