Code Explanation:
1. Defining Class A
class A:
Creates a base class named A
Inherits from object implicitly
๐น 2. Overriding __new__ in Class A
def __new__(cls):
print("A new")
return super().__new__(cls)
What __new__ does:
__new__ is responsible for creating the object
It runs before __init__
cls refers to the class being instantiated (here: B)
Line-by-line:
print("A new") → prints a message when an object is created
super().__new__(cls) → actually creates and returns the object
⚠️ If this line didn’t return an object, __init__ would never run
๐น 3. Defining Class B (Inherits from A)
class B(A):
B inherits from A
B does not override __new__
So A.__new__ is used when creating a B object
๐น 4. Defining Constructor __init__ in Class B
def __init__(self):
print("B init")
__init__ initializes an already-created object
Runs after __new__, but only if __new__ returns an object
self refers to the instance of B
๐น 5. Creating an Object of B
B()
Execution order:
Python looks for __new__
Not found in B
Found in A → A.__new__ runs
"A new" is printed
super().__new__(cls) creates the object
Python calls B.__init__
"B init" is printed
✅ Final Output
A new
B init

0 Comments:
Post a Comment