Python's Data Model: How Special Methods Shape Custom Objects

Every Python object you have ever used, from a humble list to a datetime, behaves the way it does because of the Python data model. It is the contract that tells the interpreter what len(x), x + y, x[0], for item in x, with x: and print(x) should mean for a given object. The mechanism behind that contract is a set of special methods, also called dunder methods (short for "double underscore") or magic methods.

If you can read and write special methods, you can build classes that feel native to the language. They work with built-in functions, operators, loops, and standard-library tools without any adapter code. This guide covers how the interpreter calls special methods, which ones matter most, and how to avoid the mistakes that cause subtle bugs. Every concept comes with runnable examples.

Key takeaways

  • The Python data model defines how objects interact with language syntax and built-in functions. Special methods are how your classes plug into it.
  • You almost never call special methods directly. You write len(obj), and Python calls type(obj).__len__(obj) for you.
  • Special methods are looked up on the , not on the instance. Assigning does not work.