Master Python’s __new__, __init__, and __del__ Magic Methods with Real Code Examples
This article explains how Python’s __new__, __init__, and __del__ magic methods work, shows when to use each, and provides step‑by‑step code examples—including singleton creation, inheritance initialization, resource cleanup, and metaclass usage—to help developers master object lifecycle control.
Python provides three special ("magic") methods that control an object’s lifecycle: __new__ creates a new instance, __init__ initializes the already‑created instance, and __del__ runs just before the object is destroyed.
__new__ Method
__new__is a static method invoked before __init__. It can be overridden to customize instance creation, such as implementing the singleton pattern.
__init__ Method
__init__runs after __new__ and is responsible for setting up the object’s state. It does not return a value.
__del__ Method
__del__is called when the interpreter is about to reclaim the object’s memory. It is useful for releasing external resources, but its exact timing depends on Python’s garbage‑collector.
Example Class with All Three Methods
class MyObject:
instances = []
def __new__(cls, *args, **kwargs):
print("__new__ called")
instance = super().__new__(cls)
return instance
def __init__(self, name):
print("__init__ called for {}".format(name))
self.name = name
MyObject.instances.append(self)
def __del__(self):
print("__del__ called for {}".format(self.name))
MyObject.instances.remove(self)
def __repr__(self):
return "<{} - {}>".format(self.__class__.__name__, self.name)Step‑by‑Step Demonstrations
1. Create the first object:
obj1 = MyObject('Object1')
print(MyObject.instances) # []2. Create a second object:
obj2 = MyObject('Object2')
print(MyObject.instances) # [obj1, obj2]3. Singleton using __new__:
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True4. Simple class with __init__:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person('Alice', 25)
print(p1.name, p1.age) # Alice 255. Resource cleanup with __del__:
obj3 = MyObject('Object3')
del obj3
print(MyObject.instances) # []6. Counting instances with a class variable in __new__:
class Counter:
count = 0
def __new__(cls, *args, **kwargs):
cls.count += 1
return super().__new__(cls)
c1 = Counter()
c2 = Counter()
print(Counter.count) # 27. Instance variables set in __init__:
class Account:
def __init__(self, balance=0):
self.balance = balance
a1 = Account(100)
a2 = Account(200)
print(a1.balance, a2.balance) # 100 2008. External resource release in __del__:
import os
class File:
def __init__(self, path):
self.path = path
self.file = open(path, 'w')
def __del__(self):
self.file.close()
os.remove(self.path)
f = File('temp.txt')
del f # temp.txt is deleted9. Using __new__ in a metaclass:
class Meta(type):
def __new__(cls, name, bases, dct):
print(f"Creating class {name}")
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
m = MyClass() # Output: Creating class MyClass10. Inheritance with __init__ chaining:
class Base:
def __init__(self):
print("Base initialized")
class Derived(Base):
def __init__(self):
super().__init__()
print("Derived initialized")
d = Derived()
# Output:
# Base initialized
# Derived initializedThese examples demonstrate how to control object creation, initialization, and cleanup in Python, and they illustrate common patterns such as singletons, metaclasses, and resource management. Note that the exact timing of __del__ execution can vary; you may need to invoke gc.collect() to force garbage collection.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
