Concepts / Method Definition and Calling

Method Definition and Calling

Special methods enable custom classes to mimic built-in type behaviors through double-underscore naming conventions.

  • Programming

A Familiar Expression, Hidden Call

A custom object can support familiar operations such as indexing, length checks, arithmetic, and string conversion. The important idea is that Python does not apply these expressions directly to the object in the same way a learner might imagine. Instead, Python recognizes the syntax and automatically translates it into a call to a corresponding special method.

What do you think happens?

What special method does Python use when it evaluates obj[key]?

  • __len__
  • __getitem__
  • __add__
  • __str__
Reveal answer

Answer: __getitem__

Python translates obj[key] into a call to obj.__getitem__(key). The key or index becomes the method argument, and the method returns the value associated with it.

Expression-to-Method Mapping

Special methods are methods with double-underscore names that Python recognizes for particular operations. For example, len(obj) is translated into obj.__len__(), obj[key] is translated into obj.__getitem__(key), and a + b is translated into a.__add__(b). This translation is automatic and invisible during ordinary use, but it explains how a class can define the behavior of familiar syntax.

translates totranslates totranslates toobj[key]indexing expression__getitem__(key)indexing behaviorlen(obj)length expression__len__()length behaviora + baddition expression__add__(b)addition behavior
What special method does Python invoke when an expression such as obj[key], len(obj), or obj + other is evaluated?
Familiar expressionUnderlying special methodPurpose
obj[key]obj.__getitem__(key)Indexing or key-based access
len(obj)obj.__len__()Length behavior
a + ba.__add__(b)Addition behavior
Printing or string conversion__str__Human-friendly string representation

Examples of Python expressions and the special methods that define their behavior.

Creation and Cleanup

The object lifecycle includes creation, initialization, and eventual destruction. When a new instance is created, Python automatically calls __init__. This method gives the class a place to initialize the object's state. When an object is about to be destroyed, Python calls __del__, giving the class a chance to clean up resources.

automatically callsinitializeseventually reachesautomatically callsNew instanceobject creation__init__initialize stateObjectusable instanceAbout to be destroyedcleanup stage__del__clean up resources
What happens to an object from creation through initialization and eventually to cleanup?

Indexing Through __getitem__

Following a Key Through a Custom Object

A custom class provides __getitem__. A user evaluates obj[key]. What role does the key play?

Start with familiar syntax: The user writes obj[key], using the same square-bracket form associated with lists, tuples, and other indexable objects.

Translate the expression: Python automatically interprets the expression as a call to obj.__getitem__(key).

Receive the argument: The custom method receives the key or index as its argument.

Return the value: The method returns the corresponding value, which becomes the result of obj[key].

Implementing __getitem__ allows a custom object to support familiar square-bracket indexing.

obj[key]argumentreturnsobjcustom object__getitem__receives keyvaluereturned resultkeyindex or key
How does an index or key move from obj[key] into __getitem__, and what value comes back?

The practical benefit of __getitem__ is interface familiarity. Users of the class can use square brackets instead of learning a separate access operation. The class decides what the key means and which corresponding value to return.

Behaving Like a Built-in

Desired behaviorSpecial methodEffect for users
Initialize object state__init__New instances begin with initialized state
Provide indexed access__getitem__Users can write obj[key]
Define addition__add__Objects can participate in addition behavior
Define comparisons__eq__ or __lt__Objects can participate in equality or less-than behavior
Control displayed text__str__ or __repr__Objects have appropriate string representations

This is the broader purpose of special methods: they let a custom class mimic selected behaviors of built-in Python types. Operator overloading uses methods such as __add__, __sub__, and __mul__ to define arithmetic for custom objects. Comparison methods such as __eq__ and __lt__ define comparison behavior. The class can therefore fit into expressions that users already understand.

String representation follows the same pattern. __str__ is intended to produce a human-friendly representation for end users. __repr__ is intended for developers and should ideally represent the object's state in a form that could be used to recreate it.

Mistakes with Special Methods

  • Treating obj[key] as unrelated to __getitem__

    Python translates obj[key] into obj.__getitem__(key), so the special method defines the custom indexing behavior.

    Fix: When debugging indexing, trace the expression to __getitem__ and check how the method uses the received key.

  • Using __init__ as if it were an ordinary method called manually for every access

    __init__ is called automatically when a new instance is created to initialize its state.

    Fix: Associate __init__ with object creation and initialization.

  • Confusing __str__ and __repr__

    __str__ is intended for end users, while __repr__ is intended for developers and should ideally represent the object's state in a recreatable form.

    Fix: Use the human-friendly purpose of __str__ and the developer-oriented purpose of __repr__ as the distinction.

  • Assuming an operator has fixed meaning for every custom object

    Python translates addition into a.__add__(b), so a class can define what addition means for its objects.

    Fix: When analyzing an operator on a custom object, identify the corresponding special method.

Practice the Translation

MEDIUM

For each expression, name the special method Python uses to define the relevant behavior: len(obj), obj[key], a + b, and a == b. Then explain which lifecycle method initializes a new object and which method provides cleanup when an object is about to be destroyed.

Hints
  • Indexing uses the method that receives a key or index.
  • Addition is an example of operator overloading.
  • Equality and less-than behavior are controlled by comparison special methods.
  • Creation and destruction use different lifecycle methods.

Checking Your Trace

Match four expressions to their special methods.

Length: len(obj) maps to obj.__len__().

Indexing: obj[key] maps to obj.__getitem__(key).

Addition: a + b maps to a.__add__(b).

Equality: Equality behavior is associated with __eq__.

The expression is the user-facing form; the special method is the class-level behavior Python invokes for that operation.

Key Takeaways

  1. Special methods use double-underscore names to connect custom classes with familiar Python behavior.
  2. Python automatically translates expressions such as len(obj), obj[key], and a + b into calls to specific special methods.
  3. __init__ initializes an object's state during creation, while __del__ provides an opportunity for cleanup when the object is about to be destroyed.
  4. __getitem__ enables custom objects to support square-bracket indexing.
  5. Methods such as __add__, __eq__, __str__, and __repr__ define arithmetic, comparison, and string-representation behavior.

Key Takeaways

  • Special methods allow custom classes to mimic selected built-in type behaviors.
  • Python automatically maps familiar expressions to special method calls.
  • __init__ and __del__ connect class behavior to object creation and destruction.
  • __getitem__ turns square-bracket access into customizable indexing behavior.
  • Operator and representation methods let custom objects participate naturally in expressions and display operations.