Exploring Object Behavior
Explore how Python objects control operations with special dunder methods. Understand how functions like len(), str(), and operators like + delegate behavior to objects, enabling consistent and extensible code design.
We'll cover the following...
So far, we have used functions like len() and operators like + to manipulate data. For example, len() returns the number of items in a collection, and + adds numbers or concatenates strings. However, we have not yet examined how these operations are implemented.
For example, how does a single function like len() know how to count characters in a string and elements in a list? This behavior is not magical, nor does it rely on a long chain of conditional checks for every possible data type. Instead, Python depends on a well-defined interaction between the operation and the object being operated on.
The secret life of objects
In Python, objects do more than store data. They also define how that data behaves. When we use a function or an operator, Python does not carry out the operation itself. Instead, it delegates the work to the object by invoking a special, predefined method.
These methods are easy to recognize because their names begin and end with double underscores. They are commonly referred to as dunder methods (short for “double ...