Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Module 5 - Object-Oriented Programming Python Python OOP Python Programming: From Zero to Real-World Applications

Dunder Methods - __init__, __str__, __repr__, and More

Reviewed & accurate
AI Summary

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

MethodTrigger
__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.
Previously: Lesson 35 covered encapsulation.
Today: You learned: Magic methods that make objects Pythonic.
Next: Module 5 complete! Module 6 begins with lesson 37.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments