Code Explanation:
๐น 1. Class A Definition
class A:
✅ Explanation:
A class A is created.
It overrides the special method __new__.
๐น 2. __new__ Method in Class A
def __new__(cls):
print("A new")
return super().__new__(B)
✅ Explanation:
__new__ is responsible for creating a new object (before __init__).
It runs before __init__.
๐ Step-by-step:
print("A new") → prints:
A new
super().__new__(B):
Instead of creating an object of class A
It creates an object of class B
So, the returned object is NOT of type A, but type B
๐น 3. Class B Definition
class B:
✅ Explanation:
A separate class B is defined.
It has its own constructor.
๐น 4. Constructor of Class B
def __init__(self):
print("B init")
✅ Explanation:
This runs when an object of class B is initialized.
Prints:
B init
๐น 5. Object Creation
obj = A()
✅ What happens internally:
Step 1: Call A.__new__(A)
Prints:
A new
Returns an object of class B
Step 2: Python checks returned object type
Returned object is of type B
So Python calls:
B.__init__(obj)
Step 3: Execute B.__init__
Prints:
B init
๐ฏ Final Output
A new
B init

0 Comments:
Post a Comment