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
class 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
class 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
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.
Last updated