-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinitialization.py
More file actions
30 lines (25 loc) · 895 Bytes
/
initialization.py
File metadata and controls
30 lines (25 loc) · 895 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class MyClass:
# __new__ is responsible for creating a new instance.
def __new__(cls, value):
print("Calling __new__")
instance = super().__new__(cls)
return instance
# __init__ initializes the instance (called automatically after __new__)
def __init__(self, value):
print("Calling __init__")
self.value = value
# __del__ is the destructor (called when the object is garbage-collected)
def __del__(self):
print(f"Deleting instance with value: {self.value}")
# Create an instance:
obj = MyClass(10)
print("Object value:", obj.value)
# Delete it explicitly (or wait for GC):
# __del__ will automatically be executed when the script get terminated or when the object is no longer referenced.
del obj
"""
Calling __new__
Calling __init__
Object value: 10
Deleting instance with value: 10
"""