Object-Oriented Programming
Classes are Python’s main object-oriented programming (OOP) tool. They support multiple instances, attribute inheritance, and operator overloading.
Classes and Instances
Class objects provide default behavior
The
classstatement creates a class object and assigns it to a name.Assignments inside
classstatements create class attributes, which are inherited object state and behavior.Class methods are nested
defs, with special first arguments to receive the implied subject 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 attributes of the first argument (e.g.,
self.X = V) in methods create per-instance attributes.
Inheritance rules
Inheritance happens at attribute qualification time: on
object.attribute, ifobjectis 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 from which they are generated, plus all that class’s superclasses.
Inheritance searches the instance, then its class, then all accessible superclasses, and uses the first version of an attribute name found. Superclasses are searched depth-first and then left-to-right (but new-style classes search across before proceeding up in diamond pattern trees).
Pseudoprivate Attributes ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access