Overview

15 Classes and object-oriented programming

This chapter introduces Python’s class system and shows how objects bundle data and behavior. It explains how to define classes and instantiate them, how special methods like __init__ initialize new instances (and when __new__ might matter), and how method calls are resolved via explicit self. The discussion stays focused on Python’s constructs rather than OOP theory, emphasizing Python’s explicitness, dynamic nature, and the convenience of using objects as lightweight records when needed.

Core building blocks include instance variables and the importance of explicit attribute access, methods and their invocation (bound vs unbound), and class variables—plus the “oddity” where missing instance attributes fall back to class attributes, and how assigning on an instance creates a shadowing instance attribute. The chapter contrasts @staticmethod with @classmethod (using cls to avoid hardcoding class names and to support subclasses), and covers information hiding with double-underscore name mangling for “private” attributes and methods. It also shows how @property lets you keep dot-style access while adding validation or computed values, and summarizes scoping and namespace lookup across local/global/built-in and instance/class/superclass spaces.

On reuse and extensibility, the chapter demonstrates inheritance with a Shape/Circle/Square example, the use of super() to delegate initialization, and how method lookup naturally favors subclass definitions while falling back to superclasses (all methods are effectively virtual). It explores how class and instance variables behave across inheritance, provides a gentle introduction to multiple inheritance and method resolution order, and notes that destructors are rarely needed thanks to garbage collection, with context managers preferred for external resources. A recap example and a lab exercise tie these ideas together, highlighting practical patterns for organizing behavior in base classes and keeping subclasses minimal.

Direct namespaces
self variable namespaces
Inheritance hierarchy

Summary

  • Defining a class in effect creates a new data type.
  • __init__ is used to initialize data when a new instance of a class is created, but it isn’t a constructor.
  • The self parameter refers to the current instance of the class and is passed as the first parameter to methods of a class.
  • Static methods can be called without creating an instance of the class, so they don’t receive a self parameter.
  • Class methods are passed a cls parameter, which is a reference to the class, instead of self.
  • All Python methods are virtual. That is, if a method isn’t overridden in the subclass or private to the superclass, it’s accessible by all subclasses.
  • Class variables are inherited from superclasses unless they begin with two underscores (__), in which case they’re private and can’t easily be seen by subclasses. Methods can be made private in the same way.
  • Properties let you have attributes with defined getter and setter methods, but they still behave like plain instance attributes.
  • Python allows multiple inheritance, which is often used with mixin classes.

FAQ

How do I define a class and create an instance in Python?Use the class statement and instantiate by calling the class like a function. Example: class MyClass: pass; then obj = MyClass(). By convention, class names use CapCase.
What are instance variables, and how do I create and access them?Instance variables belong to a specific object and are created by assignment to self.name inside methods or obj.name = value from outside. Inside methods, always use self.name; a bare name refers to a local variable, not an instance attribute.
How do methods work in classes, and what does self mean?Methods are functions defined in a class whose first parameter is the instance (conventionally self). Calling obj.m(a, b) is equivalent to Class.m(obj, a, b) (a “bound” call). You can also call via the class (uncommon) by explicitly passing the instance.
What’s a class variable, and how should I access it?A class variable is defined in the class body and shared by all instances, e.g., class C: x = 10. Access via C.x or from methods as C.x or self.__class__.x to avoid hardcoding the class name.
Why does accessing a class variable through an instance sometimes behave oddly?If an instance lacks attribute a, Python falls back to the class attribute a. But assigning obj.a = value creates an instance attribute that shadows the class variable. To change the class variable for all instances, assign to ClassName.a, not obj.a.
When should I use @staticmethod vs @classmethod?Use @staticmethod for utility functions that don’t need instance or class context. Use @classmethod when the method needs the class (passed as cls)—for example, to work with class variables or to support subclass-friendly behavior without hardcoding the base class name.
How does inheritance work, and why call super().__init__?Declare with class Sub(Base):. In Sub.__init__, call super().__init__(...) to initialize the base part. Method lookup searches instance → class → superclasses; all methods are effectively virtual.
Does Python support multiple inheritance? How are name conflicts resolved?Yes. List bases left-to-right: class A(B, C, D):. Python’s method resolution order (MRO) searches the class, then the first base and its ancestors before moving to the next base, ensuring each class is visited once. Prefer mixins and avoid name clashes; use super() cooperatively.
How do I make variables or methods “private” in Python?Prefix the name with double underscores (e.g., __y). Python “name-mangles” it to _ClassName__y, preventing accidental access and superclass/subclass name clashes. It’s not strict security; access is still possible if you know the mangled name.
What is @property and how does it help manage attributes?@property lets you expose a computed or validated attribute with normal dot syntax. Define a getter with @property and, if needed, a setter with @attr.setter. This keeps client code unchanged while adding validation (e.g., forbidding negative sizes) or computed conversions.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free