Object-Oriented Programming

Classes are Python’s main OOP tool. They support multiple copies, attribute inheritance, and operator overloading.

Classes and Instances

Class Objects Provide Default Behavior

  • The class statement creates a class object and assigns it to a name.

  • Assignments inside class statements create class attributes, which export object state and behavior.

  • Class methods are nested defs, with special first arguments to receive the instance.

Instance Objects Are Generated from Classes

  • Calling a class object like a function makes a new instance object.

  • Each instance object inherits class attributes, and gets its own attribute namespace.

  • Assignments to the first argument (“self”) in methods create per-instance attributes.

Inheritance Rules

  • Inheritance happens at attribute qualification time: on object.attribute, if object is a class or instance.

  • Classes inherit attributes from all classes listed in their class statement header line (superclasses). Listing more than one means multiple inheritance.

  • Instances inherit attributes from the class they are generated from, plus all its superclasses.

  • Inheritance searches the instance, then its class, then all accessible superclasses (depth-first, left-to-right) and uses the first version of an attribute name found.

Special Overloading Methods

Classes intercept and implement built-in operations by providing specially-named method functions, which all start and end with two underscores. Python calls a class’s overloading methods automatically when ...

Get Python Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.