25. Python's __magic__ Methods
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.
1. __init__: Constructor Method
__init__: Constructor Methodclass Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(p.name) # Alice
print(p.age) # 302. __str__: String Representation for Humans
__str__: String Representation for Humansclass Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old."
p = Person("Alice", 30)
print(p) # Alice is 30 years old.3. __repr__: String Representation for Debugging
__repr__: String Representation for Debugging4. __add__: Overloading the + Operator
__add__: Overloading the + Operator5. __getitem__: Index Access for Custom Objects
__getitem__: Index Access for Custom Objects6. __len__: Custom Length Calculation
__len__: Custom Length Calculation7. __eq__: Overloading == for Equality Check
__eq__: Overloading == for Equality Check8. __call__: Making Objects Callable
__call__: Making Objects Callable9. __del__: Destructor Method
__del__: Destructor Method10. __contains__: Custom Behavior for in
__contains__: Custom Behavior for inThese 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.
Last updated