Tutorials / Python: Intermediate to Advanced / Properties and special (dunder) methods

Properties and special (dunder) methods

15 min read python
Course contents (15 lessons)
  1. Iteration the Python way
  2. List, dict and set comprehensions
  3. Iterators and generators
  4. Functions as building blocks
  5. Closures and decorators
  6. Context managers and the with statement
  7. Object-oriented Python in depth
  8. Classes and dataclasses
  9. Properties and special (dunder) methods
  10. Inheritance versus composition
  11. Quality: types, packaging and tests
  12. Type hints and mypy
  13. Packaging a project with pyproject.toml
  14. Testing with pytest
  15. Async code and web APIs
  16. async and await with asyncio
  17. Working with HTTP APIs and JSON
  18. Performance, concurrency and a final project
  19. Performance and profiling
  20. Concurrency: threads versus processes
  21. Final project: a price tracker command-line tool

Attributes with rules

In some languages you hide every field behind getter and setter methods from day one. In Python you do not. Start with a plain attribute. If you later need validation or a computed value, turn it into a property and callers do not have to change a thing.

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price        # goes through the setter below

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError("price cannot be negative")
        self._price = value

    @property
    def price_with_tax(self):     # computed, read-only
        return round(self._price * 1.17, 2)


p = Product("Tea", 120)
p.price = 130                    # looks like a plain attribute
print(p.price_with_tax)          # 152.1
# p.price = -5                   # ValueError
# p.price_with_tax = 1           # AttributeError: no setter

The underscore in _price is a convention that means "internal, please use the property". Python does not enforce it. Notice that __init__ assigns to self.price, not self._price, so the validation also runs when the object is created. Forgetting that is a common slip, and it lets bad values in through the constructor.

Dunder methods

Methods with double underscores on both sides, like __init__, are called dunder (double underscore) or special methods. Python calls them for you when you use operators and built-in functions. By defining them, your classes can behave like lists, numbers or anything else. The idea is that len(x) secretly calls x.__len__(), and a + b calls a.__add__(b).

Here is a shopping cart that acts like a collection and supports adding carts together:

class Cart:
    def __init__(self, items=None):
        self._items = dict(items or {})     # name -> quantity

    def add(self, name, qty=1):
        self._items[name] = self._items.get(name, 0) + qty

    def __len__(self):
        return sum(self._items.values())

    def __iter__(self):
        return iter(self._items.items())

    def __getitem__(self, name):
        return self._items[name]

    def __contains__(self, name):
        return name in self._items

    def __add__(self, other):
        if not isinstance(other, Cart):
            return NotImplemented
        merged = Cart(self._items)
        for name, qty in other:
            merged.add(name, qty)
        return merged

    def __eq__(self, other):
        if not isinstance(other, Cart):
            return NotImplemented
        return self._items == other._items

    def __bool__(self):
        return bool(self._items)

    def __repr__(self):
        return f"Cart({self._items!r})"


a = Cart()
a.add("tea", 2)
b = Cart({"tea": 1, "sugar": 3})
both = a + b

print(both)                  # Cart({'tea': 3, 'sugar': 3})
print(len(both))             # 6
print("tea" in both)         # True
print(both["sugar"])         # 3
print(bool(Cart()))          # False
for name, qty in both:
    print(name, qty)

How the pieces behave

__len__ makes len(cart) work. __iter__ makes the cart usable in a for loop. __getitem__ makes cart["tea"] work. __contains__ powers the in operator. __bool__ decides truthiness, and without it Python would fall back on __len__. And __add__ handles the + operator.

Look at what __add__ and __eq__ do when the other object is not a Cart: they return NotImplemented, which is a special value, not an exception. It tells Python "I do not know how to do this, try the other object's method". If both give up, Python raises a proper TypeError for you. Raising a TypeError yourself, or returning False, is a typical mistake that breaks mixed-type comparisons.

repr and str

__repr__ should give an unambiguous description for developers, ideally something that looks like the code to create the object. __str__ gives a friendly text for users and is used by print. If you define only one, define __repr__, since str() falls back on it. Printing objects in a debugger or in a log is far easier when __repr__ exists.

Equality and hashing

Here is a trap: if you define __eq__ and not __hash__, Python sets __hash__ to None and your objects can no longer go in sets or be dictionary keys. Our mutable Cart should not be hashable anyway, so that is correct. For immutable value types, define both consistently, or use a frozen dataclass and get them for free.

Ordering

To make objects sortable, define __lt__. Decorate the class with functools.total_ordering and define __eq__ plus one of the ordering methods, and the rest are generated. For most records, a dataclass with order=True is shorter.

Other useful ones

  • __call__ makes an instance callable like a function.
  • __enter__ and __exit__ make a context manager, as in the previous lessons.
  • __getattr__ runs when normal attribute lookup fails, useful for proxies. Be careful, as it can hide typos.
  • __slots__ restricts attributes and saves memory.

Do not overdo it

Operator overloading is powerful, but only use it where the meaning is obvious. cart_a + cart_b is clear. Using * to mean "send an email" would not be. When in doubt, write a normal method with a descriptive name.

Try it yourself

Write a Money class with an integer paisa amount. Add __add__, __sub__, __mul__ (multiply by an integer), __eq__, __lt__, __hash__, __repr__ and a __str__ that shows Rs 1,250.50. Make sure Money(100) + 5 raises TypeError, and that you can sort a list of Money objects.

python
class Cart:
    def __init__(self, items=None):
        self._items = dict(items or {})     # name -> quantity

    def add(self, name, qty=1):
        self._items[name] = self._items.get(name, 0) + qty

    def __len__(self):
        return sum(self._items.values())

    def __iter__(self):
        return iter(self._items.items())

    def __getitem__(self, name):
        return self._items[name]

    def __contains__(self, name):
        return name in self._items

    def __add__(self, other):
        if not isinstance(other, Cart):
            return NotImplemented
        merged = Cart(self._items)
        for name, qty in other:
            merged.add(name, qty)
        return merged

    def __eq__(self, other):
        if not isinstance(other, Cart):
            return NotImplemented
        return self._items == other._items

    def __bool__(self):
        return bool(self._items)

    def __repr__(self):
        return f"Cart({self._items!r})"


a = Cart()
a.add("tea", 2)
b = Cart({"tea": 1, "sugar": 3})
both = a + b

print(both)                  # Cart({'tea': 3, 'sugar': 3})
print(len(both))             # 6
print("tea" in both)         # True
print(both["sugar"])         # 3
print(bool(Cart()))          # False
for name, qty in both:
    print(name, qty)

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account