Code Explanation:
1. Class Definition
class A:
This line defines a class named A.
Classes are blueprints for creating objects.
2. __new__ Method (Object Creation)
def __new__(cls):
__new__ is a special method.
It is responsible for creating a new instance of the class.
cls refers to the class itself (not an object yet).
2.1 Calling Parent’s __new__
return super().__new__(cls)
super().__new__(cls) calls the __new__ method of the parent class (object).
This actually allocates memory for the new object.
The newly created instance is returned.
If __new__ does not return an instance of cls, __init__ will not run.
3. __init__ Method (Object Initialization)
def __init__(self):
__init__ is called after __new__.
self refers to the already created object.
This method is used to initialize the object.
3.1 Print Statement
print("Init")
Prints the string "Init" when an object of class A is created.
4. Object Creation
A()
This line creates an object of class A.
Execution flow:
__new__ is called → object is created
__init__ is called → object is initialized
"Init" is printed
5. Output
Init

0 Comments:
Post a Comment