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
Copy
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
Copy
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
Copy
4. __add__: Overloading the + Operator
Copy
5. __getitem__: Index Access for Custom Objects
Copy
6. __len__: Custom Length Calculation
Copy
7. __eq__: Overloading == for Equality Check
Copy
8. __call__: Making Objects Callable
Copy
9. __del__: Destructor Method
Copy
10. __contains__: Custom Behavior for in
Copy
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