Python Dunder Methods: What __init__ and __str__ Really Mean

3D isometric illustration of a robot being built (init) and labeled (str), representing Python magic methods.

“Dunder” is short for “Double Underscore.” Dunder methods are special “magic” methods that Python reserves for its own use. You don’t call them directly, but Python calls them for you in specific situations.

They are the reason len(my_list) works, and why print(my_object) knows what to do.

1. __init__ (The Constructor)

You’ve already seen this in our OOP Guide.

  • When does it run? Automatically, when you create a new object from a class.
  • What does it do? It “initializes” the object, setting up its starting attributes.
class Car:
    def __init__(self, brand):
        self.brand = brand
        print(f"A new {brand} car was created!")

my_car = Car("Tesla") # The __init__ method runs right here!
# Output: A new Tesla car was created!

2. __str__ (The “String” Representation)

By default, if you try to print() your own object, you get an ugly message: <__main__.Car object at 0x10f1abc90>

The __str__ method lets you define a clean, human-readable string to show instead.

  • When does it run? Automatically, when you use print() or str() on your object.
class Car:
    def __init__(self, brand):
        self.brand = brand
    
    def __str__(self):
        # Must return a string!
        return f"A beautiful {self.brand} car"

my_car = Car("Tesla")
print(my_car) # The __str__ method runs here!
# Output: A beautiful Tesla car

Similar Posts

Leave a Reply