Dunder Methods

Python has special methods surrounded by double underscores — called dunder methods(short for "double under"). They let you define how your objects behave with built-in operations like print(), ==, and sorting.

__str__ — Human-Readable Output

Python calls __str__ when you use print(obj) or str(obj). Without it, you get something like <__main__.Student object at 0x7f...>.

class Book:
    def __init__(self, title, author):
        self.title  = title
        self.author = author
    def __str__(self):
        return f"{self.title} by {self.author}"
b = Book("1984", "Orwell")
print(b)  # → 1984 by Orwell
1984 by Orwell

__eq__ — Equality Comparison

By default, == checks whether two variables point to the same object. Override __eq__ to define logical equality.

class Book:
    def __eq__(self, other):
        return self.title == other.title
b1 = Book("1984", "Orwell")
b2 = Book("1984", "E. Orwell")  # same title, different author
print(b1 == b2)  # → True  (titles match)
True

Other Useful Dunder Methods

  • __repr__(self) — unambiguous representation for developers (shown in REPL)
  • __lt__(self, other) — defines <; enables sorted()
  • __len__(self) — defines len(obj)
  • __getitem__(self, key) — defines obj[key] access
class Student:
    def __lt__(self, other):
        return self.name < other.name
students = [Student("Zara","B"), Student("Alice","A")]
print([s.name for s in sorted(students)])  # → ["Alice", "Zara"]

Your Task

  1. Implement __str__: return f"Student({self.name}, {self.grade})"
  2. Implement __eq__: return True if self.name == other.name

Student("Bob","B") == Student("Bob","A") should be True (same name).Student("Alice","A") == Student("Bob","B") should be False.

Section 1/4__str__ — Human-Readable Output

__str__ — Human-Readable Output

Python calls __str__ when you use print(obj) or str(obj). Without it, you get something like <__main__.Student object at 0x7f...>.

Dunder Methods

Python has special methods surrounded by double underscores — called dunder methods(short for "double under"). They let you define how your objects behave with built-in operations like print(), ==, and sorting.

__str__ — Human-Readable Output

Python calls __str__ when you use print(obj) or str(obj). Without it, you get something like <__main__.Student object at 0x7f...>.

class Book:
    def __init__(self, title, author):
        self.title  = title
        self.author = author
    def __str__(self):
        return f"{self.title} by {self.author}"
b = Book("1984", "Orwell")
print(b)  # → 1984 by Orwell
1984 by Orwell

Output:

Click "Check" to run your code.