Here Python code snippets that showcase the use of Python's dunder methods (a.k.a. magic methods) like __init__, __str__, __repr__, and others, to customize class behavior.
classPerson:def__init__(self,name,age):self.name = nameself.age = agedef__str__(self):returnf"{self.name} is {self.age} years old."p =Person("Alice",30)print(p)# Alice is 30 years old.
3. __repr__: String Representation for Debugging
4. __add__: Overloading the + Operator
5. __getitem__: Index Access for Custom Objects
6. __len__: Custom Length Calculation
7. __eq__: Overloading == for Equality Check
8. __call__: Making Objects Callable
9. __del__: Destructor Method
10. __contains__: Custom Behavior for in
These examples demonstrate how dunder methods let you override and customize the behavior of built-in Python operations, allowing you to create intuitive, powerful, and expressive classes.
class Resource:
def __init__(self, name):
self.name = name
print(f"Resource {self.name} created.")
def __del__(self):
print(f"Resource {self.name} destroyed.")
res = Resource("FileHandler")
del res # Resource FileHandler destroyed.
class CustomContainer:
def __init__(self, items):
self.items = items
def __contains__(self, item):
return item in self.items
container = CustomContainer([1, 2, 3])
print(2 in container) # True
print(5 in container) # False