O'Reilly logo

Python Pocket Reference by Mark Lutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required