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?