liveBook · Manning

Special method

A special method is a Python method with a conventionally reserved name that defines an object's behavior for language operations or built-in functions.

How 3 Manning books explain it

The Quick Python Book, Fourth Edition

A special method is a Python method with a conventionally reserved name that defines object behavior for language operations or built-in functions.

How it is used
Lets user-defined classes respond to Python operations and built-in functions through familiar syntax.
How deep it goes
Works through __str__ and indexed access and assignment, while noting that full list emulation needs additional methods.
Examples
Uses a printable RGB color, a type-checked list, and a file-backed line reader to show different operation choices.
What you can do after
Build it from scratch by defining methods for printing or indexed access and assignment in a user-defined class.

Read how The Quick Python Book, Fourth Edition explains special method →

Get Programming: Learn to code with Python

A special method is a Python method with a predefined double-underscore name that is invoked implicitly by language syntax or explicitly as a regular method.

How it is used
Customizes user-defined classes so operators, printing, and object creation work through familiar Python notation.
How deep it goes
Explains naming, implementation, examples, errors, and equivalent calls, stopping short of a complete catalog of special methods.
Examples
Uses Fraction arithmetic, printed fractions, and suggested Circle and Stack string representations.
What you can do after
Build it from scratch by adding operator and string-display behavior to custom classes and rewriting shorthand calls explicitly.

Read how Get Programming: Learn to code with Python explains special method →

Python How-To

A special method is a Python method with a language-defined naming convention and protocol role, commonly using double underscores to control built-in object behavior.

How it is used
Uses protocol methods to customize representations, construction, call syntax, attribute lookup, and other built-in object behavior.
How deep it goes
Explains overriding with concrete __str__, __repr__, __call__, and __getattr__ examples, while noting that attribute resolution is simplified.
Examples
Demonstrates custom representations, a class-based timing decorator, boilerplate data classes, and cached profile-data lookup.
What you can do after
Build it from scratch by overriding protocol methods that make custom objects printable, callable, constructible, or lazily populated.

Read how Python How-To explains special method →

Related concepts

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.