Overview

10 Objects

This chapter introduces Python’s object model and shows why bundling data (nouns) with behavior (verbs) into objects clarifies program structure and intent. It explains how defining domain-specific types raises the level of abstraction, shortens communication, and separates interface from implementation, while also cautioning that object orientation is not a cure‑all and can be misused (e.g., giant classes or tangled hierarchies). Although Python mixes paradigms freely, “everything is an object,” and the language’s consistency lets once-learned rules apply broadly.

You learn the core mechanics of classes, instances, attributes, and methods; how __init__ sets state after construction; and why self is an explicit first parameter. The text contrasts procedural and object-oriented styles, covers representation methods, and distinguishes instance versus class attributes, including using class attributes as configuration-like “constants.” It emphasizes composition (“has‑a”) over inheritance (“is‑a”), then shows judicious inheritance with super and method overriding. Attribute lookup follows a predictable search path (instance → class → parents → object), and dataclasses are presented as a way to reduce boilerplate while keeping Python’s dynamic feel.

Hands-on exercises progress from simple to rich models: a Scoop and Bowl to practice attributes, composition, and class-level limits; a BigBowl subclass that changes behavior by overriding only configuration; a FlexibleDict that subclasses dict and overrides __getitem__ to demonstrate customizing built-ins; and a small zoo domain (Animals, Cages, Zoo) that combines inheritance, composition, and Pythonic iteration (comprehensions, generator expressions) to query and aggregate data. By the end, you can design small, cohesive types, reuse behavior through inheritance where it fits, prefer composition for structure, and comfortably mix object-oriented, procedural, and functional techniques in readable Python code.

Three instances of Scoop, each referring to its class
9 1
Our three instances of Scoop in a list
9 2
A new instance of Bowl, with an empty list of scoops
9 7
Three Scoop objects in our bowl
9 8
max_scoops sits on the class, so even an empty instance has access to it.
9 11
A Bowl instance containing scoops, with max_scoops defined on the class
9 12
Wolf inherits from Animal. Notice which methods are defined where.
9 13
A Cage instance containing one wolf and one sheep
9 14

Summary

Object-oriented programming is a set of techniques, but it’s also a mindset. In many languages, object-oriented programming is forced on you, such that you’re constantly trying to fit your programming into its syntax and structure. Python tries to strike a balance, offering all of the object-oriented features we’re likely to want or use, but in a simple, nonconfrontational way. In this way, Python’s objects provide us with structure and organization that can make our code easier to write, read, and (most importantly) maintain.

FAQ

What problem does object-oriented programming solve compared to procedural code?It groups data (nouns) together with the functions (verbs) that operate on that data. Instead of keeping lists of values in one place and functions in another, a class bundles both, making code more organized, semantic, and easier to reason about and maintain.
What are objects, classes, and methods in Python?An object is an instance of a class (its type). A class defines the structure and behavior for its objects. Methods are functions defined on the class that operate on instances (accessed through the first parameter, conventionally named self).
What does __init__ do, and how is it different from __new__?__new__ creates the instance (the actual constructor). __init__ runs after creation to initialize the instance by setting attributes on self. __init__ shouldn’t return anything; its job is to attach state, not to create the object.
Why is the first parameter of instance methods called self?It’s a convention (not a keyword) that refers to the current instance. Python passes the instance explicitly to methods; naming it self makes code clear and tooling-friendly. You could name it differently, but you shouldn’t.
When should I use composition instead of inheritance?Use composition for “has-a” relationships (a Bowl has Scoops). Use inheritance for “is-a” relationships (a BigBowl is-a Bowl). Favor composition by default; inherit when a subtype truly extends or specializes the parent’s behavior.
How does Python look up attributes (ICPO)?Python checks in order: Instance → Class → Parents → object. The first match wins. This explains why methods are defined on classes but callable on instances, and why an instance attribute can shadow a class attribute with the same name.
What are class attributes, and how do they differ from instance attributes?Class attributes live on the class and are shared by instances (e.g., Bowl.max_scoops). Instance attributes live on each object (e.g., self.scoops). Assigning to an attribute via an instance (one_bowl.max_scoops = 7) creates or overrides an instance attribute and doesn’t change the class attribute.
When and how should I use super()?Use super() to call parent methods (commonly __init__) without naming the parent explicitly, preserving proper method resolution, DRYness, and maintainability (e.g., super().__init__(...) in a subclass to initialize base parts).
What does @dataclass do, and when should I use default_factory?@dataclass generates boilerplate like __init__ and a helpful __repr__ based on type-annotated fields. For mutable default values (like lists), use field(default_factory=list) to create a new object per instance instead of sharing one.
Is it OK to subclass built-ins like dict, and how do I avoid pitfalls?It’s possible and sometimes useful (e.g., FlexibleDict overriding __getitem__), but be cautious: unorthodox behavior can reduce clarity. When overriding special methods (like __getitem__), call the parent implementation directly (dict.__getitem__(self, key)) to avoid infinite recursion.

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
  • Python Workout, Second 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
  • Python Workout, Second 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
  • Python Workout, Second Edition ebook for free