What You Will Learn
Intermediate
- What dunder methods are
- __str__ vs __repr__
- Operator overloading
Terminalpython
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self): # Human-readable (print)
return f"Point({self.x}, {self.y})"
def __repr__(self): # Developer-readable (debugging)
return f"Point(x={self.x}, y={self.y})"
def __add__(self, other): # Overload + operator
return Point(self.x + other.x, self.y + other.y)
def __eq__(self, other): # Overload == operator
return self.x == other.x and self.y == other.y
def __len__(self): # len(point)
return 2
p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1) # Point(1, 2) - uses __str__
print(p1 + p2) # Point(4, 6) - uses __add__
print(p1 == Point(1, 2)) # True - uses __eq__
print(len(p1)) # 2 - uses __len__Common Dunder Methods
| Method | Trigger |
|---|---|
__init__ | Object creation |
__str__ | print(obj), str(obj) |
__repr__ | repr(obj), debugging |
__len__ | len(obj) |
__eq__ | obj1 == obj2 |
__add__ | obj1 + obj2 |
__getitem__ | obj[key] |
__contains__ | x in obj |
Practical Exercise
Create a class with __init__ and __str__
Print the object - see __str__ output
Add __add__ to overload + operator
Add __eq__ to compare objects with ==
Add __len__ to support len(obj)
Key Takeaways
- Dunder methods start and end with __ (double underscore).
- __init__: constructor. __str__: print. __repr__: debugging.
- __add__ overloads +. __eq__ overloads ==.
- They make your objects behave like built-in types.
- Operator overloading = defining what +, ==, etc. do for your class.
Comments
Comments
Post a Comment