0

recently I'm leanring about python magic method, in __new__ we always rewrite it by

class A:
    def __new__(cls):
        # ......
        return super().__new__(cls)

    def __init__(self):
        # .....

this method will return an A object then A will execute __init__.
so, I try the following script



class A:
    def __init__(self):
        print('A.__init__')
        self.a = 20


class B:
    def __new__(cls):
        print('B.__new__')
        return super().__new__(A)

    def __init__(self):
        print('B.__init__')
        self.b = 30


t = B()
print(type(t))

then I get result

B.__new__
<class '__main__.A'>

In my opinion, B.__new__ return an A object as it shows, then it should execute A.__init__ method, but in fact neither A.__init__ nor B.__init__ executed, object t is an A object but it have nothing relate to A or B, this confuse me, what does cls in __new__ method act as?

Xhhhhh
  • 35
  • 6

1 Answers1

2

In my opinion, B.__new__ return an A object as it shows, then it should execute A.__init__ method

That assumption is incorrect. Let's look at the code that creates instances. In python this would be the type.__call__ method. The C implementation can be found here

The three interesting steps that happen are:

  1. call type.__new__(type, ...) (here)
  2. abort when the return value of __new__ is not a sub class of the type (here)
  3. call __init__ on the created object (here)

Or in python code:

# t = B() is roughly equivalent to

t = B.__new__()  # which returns `A.__new__()`
if ìssubclass(type(t), B):  # False
    t.__init__()  # never called

Your implementation of B.__new__ however creates an object of type A. Because of that the issubclass check fails and no __init__ is called.

To summarize: B.__init__ is not called, because B.__new__ did not create an object of type B and A.__init__ was not called, because the class object A was not responsible for creating the instance (B was).

The end result is, that t is an instance of class A but its __init__ was not called. That's why t is not initialized.

Wombatz
  • 4,958
  • 1
  • 26
  • 35