Skip to content
Learn Netverks

Lesson

Step 20/36 56% through track

dunder-methods

Dunder methods

Last reviewed May 28, 2026 Content v20260528
Track mode
server_script
Means
Server runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Dunder methods: the syntax, patterns, and safety habits you need before advancing in Python.

Classes and magic methods underpin Django models and dataclasses—OOP is lighter than Java but still essential.

You will apply Dunder methods in contexts like: Scripts, Django/FastAPI apps, notebooks, and glue code between systems.

Write Python 3 in the editor and click Run on server—the dev runner executes your script with print() for output; stdlib only in playground snippets (LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Dunder (double underscore) methods hook into Python's data model—__str__, __repr__, __len__, __eq__, and operators like __add__. They let your objects behave like built-ins.

Common dunders

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    def __eq__(self, other):
        return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)

__str__ vs __repr__

__repr__ targets developers—ideally valid Python to recreate the object. __str__ targets users—pretty display. print uses __str__, falling back to __repr__.

Important interview questions and answers

  1. Q: __eq__ vs is?
    A: == calls __eq__; is checks object identity (same id in memory).
  2. Q: Why implement __repr__?
    A: Debugging and REPL clarity—shows unambiguous object state.

Self-check

  1. Which dunder does len(obj) call?
  2. What is the goal of a good __repr__?

Tip: Implement __repr__ for debugging—developers see unambiguous object state in logs.

Interview prep

__eq__ vs is?

== value equality via __eq__; is identity (same object id).

__repr__ vs __str__?

__repr__ for developers; __str__ for user-friendly display—print prefers __str__.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • __str__ vs __repr__?
  • __init__ only?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump