Chuyển đến nội dung

Bài 77 · Object-Oriented Programming

Special (Dunder) Methods

Make your Python classes feel built in. Learn __str__ and __repr__, comparisons, __len__, __getitem__, iteration and operator overloading with clear examples.

Why does len() work on lists, strings and dictionaries, and + work on numbers and strings? Because each of those types defines special methods: methods with double underscores on both sides, such as __len__ and __add__. Python developers call them dunder methods ("double underscore").

You never call them directly. Instead, Python calls them for you when you use built-in syntax: len(x) calls x.__len__(), a + b calls a.__add__(b), and print(x) calls x.__str__(). By defining these methods in your own classes, you make your objects work with the same syntax as Python's built-in types. You've already used one: __init__.

Printing objects: __repr__ and __str__

By default, printing an object shows something unhelpful like <__main__.Book object at 0x7f...>. Two methods fix that:

  • __repr__ returns an unambiguous, developer-facing description. Ideally it looks like the code that would recreate the object. The REPL, debuggers, and containers such as lists use it.
  • __str__ returns a friendly, user-facing text. print() and str() use it. If you don't define it, Python falls back to __repr__.
Python __repr__ and __str__

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Tip: If you only write one, write __repr__. It improves debugging output everywhere, and print() will use it too. The !r inside the f-string adds quotes around strings, so the output matches real Python code.

Equality: __eq__

Out of the box, == on two objects checks whether they are the very same object, just like is. Two separate books with identical data are "not equal". Define __eq__ to compare by value:

Python __eq__

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details matter here:

  • Returning NotImplemented (a special built-in value, not an exception) tells Python "I don't know how to compare with that type". Python then tries the other object's method, and if nothing works, == falls back to False.
  • When you define __eq__, Python sets __hash__ to None, which makes the objects unusable in sets and as dictionary keys. If your object should be hashable, define __hash__ from the same fields you compare. Only do this for objects whose fields won't change, because a changing hash breaks sets and dicts.

Ordering: __lt__ and friends

The comparison operators each have a method: __lt__ (<), __le__ (<=), __gt__ (>) and __ge__ (>=). Writing all four is tedious, so the functools.total_ordering decorator fills in the rest from __eq__ and one of them:

Python Sorting custom objects

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

As strings, "1.10.0" sorts before "1.2.3". Comparing tuples of numbers gets it right. sorted(), min() and max() only need <, so __lt__ alone is enough for sorting, but total_ordering makes every operator work.

Containers: __len__, __getitem__, __contains__, __iter__

Special methods let your class act like a collection:

Syntax Method called
len(obj) obj.__len__()
obj[key] obj.__getitem__(key)
obj[key] = value obj.__setitem__(key, value)
item in obj obj.__contains__(item)
for x in obj obj.__iter__()
bool(obj), if obj: obj.__bool__(), or __len__ if missing
Python A playlist that acts like a list

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Because __getitem__ passes the index straight to the inner list, slices and negative indexes work without extra code. __iter__ returns an iterator, as you learned in Iterators and the Iteration Protocol. And since there's no __bool__, Python uses __len__: an empty playlist is falsy, matching how built-in containers behave.

Operator overloading

Arithmetic operators map to methods too: __add__ (+), __sub__ (-), __mul__ (*), __truediv__ (/), and more. Defining them is called operator overloading:

Python A Money class with operators

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line raises a ValueError on purpose. Notice the reflected methods: for 3 * coffee, Python first tries int.__mul__(3, coffee). The int doesn't know about Money and returns NotImplemented, so Python tries coffee.__rmul__(3). The same trick, __radd__, makes sum() work, because sum() starts with 0 + first_item.

Operator overloading should follow common sense. + on money values clearly means "add"; + on two user accounts would just confuse readers. Python itself overloads + for list and string concatenation and | for set union and dict merging.

In-place operators

What about +=? Python first looks for an in-place method such as __iadd__. If the class doesn't define one, it falls back to __add__ and rebinds the name to the result: total += cake becomes total = total + cake. For immutable values like Money (and Python's own numbers, strings and tuples) that fallback is exactly right, because each operation produces a new object.

Mutable containers are different. Lists define __iadd__ to extend the existing list in place, which is why += on a list changes it for every name that refers to it, while a = a + [4] creates a new list. When you write your own mutable classes, decide deliberately which behavior you want, and be consistent with the built-in types.

Other useful special methods

You'll meet more of these as you go. A few worth knowing by name:

  • __call__ makes an instance callable like a function: obj(arg).
  • __enter__ and __exit__ make an object work with with; see Context Managers.
  • __hash__ controls hashing for sets and dict keys.
  • __format__ customizes format specs in f-strings, such as f"{obj:short}".

Note: Don't invent your own dunder names like __mything__. Python reserves the double-underscore-on-both-sides pattern for itself, and a future version could give your name a meaning.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Which method does print(obj) use first?

    print() calls str(), which uses __str__ when it exists and __repr__ otherwise.
  2. 2. What should __eq__ return when the other object is a type it doesn't understand?

    NotImplemented lets Python try the other operand's method before giving up.
  3. 3. You defined __eq__ but not __hash__. What happens when you put the objects in a set?

    Defining __eq__ sets __hash__ to None. Add __hash__ based on the same fields to make objects hashable again.
  4. 4. Which method lets 3 * price work when price is your own class?

    int.__mul__ returns NotImplemented, so Python calls the reflected method on the right operand: price.__rmul__(3).
  5. 5. A class defines __len__ but not __bool__. When is an instance falsy?

    Without __bool__, Python uses __len__, so an empty container-like object is falsy.

Summary

  • Special (dunder) methods connect your classes to Python syntax: len(), ==, <, +, [], in, for and more.
  • __repr__ is for developers (unambiguous), __str__ for users; write __repr__ first.
  • __eq__ compares by value; return NotImplemented for unknown types and add __hash__ if objects must be hashable.
  • functools.total_ordering builds all comparisons from __eq__ plus __lt__.
  • __len__, __getitem__, __contains__ and __iter__ make container-like classes.
  • Arithmetic operators map to __add__, __mul__ and friends; reflected methods like __rmul__ handle the other operand order.

Next: Properties, where you'll control attribute access with @property for computed values and validation.

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.