Python Classes

Classes, Inheritance and Composition in Python

Learn to design Python classes that work together. Build class hierarchies with inheritance and super(), predict the method resolution order when a class has several bases, and override methods so that one call works across many classes. Decide when composition fits better than inheritance, require methods with abstract base classes, give your objects built-in behavior with special methods, control attributes with properties, and write compact, safe data classes with @dataclass.

IntermediateLesson 1 of 9 in Intermediate Python Course

What you will learn

  1. Create subclasses that reuse and extend a base class, set them up correctly with super(), and predict which method Python runs when a class has one base or several.
    • Create subclasses and trace attribute lookup
      Define a subclass, explain the is-a relationship it expresses, and trace how Python finds an attribute through the instance, its class and the base classes.
    • Set up subclasses with super()
      Extend the base class's __init__ and other methods with super(), so a subclass adds its own data without repeating or skipping the base class's setup.
    • Use multiple inheritance, the MRO and mixins
      Predict the method resolution order of a class with several bases, write cooperative methods with super(), and add a reusable capability with a mixin class.
  2. Replace and extend inherited behavior, write code that works with any object offering the right methods, and require those methods with abstract base classes.
    • Override and extend inherited methods
      Replace an inherited method, extend it with super(), keep the override compatible with the base class, and write class methods that create the right subclass.
    • Use polymorphism and duck typing
      Call the same method on objects of different classes, let each class respond in its own way, and rely on what an object can do rather than on its exact type.
    • Define required methods with abstract base classes
      Write abstract base classes with the abc module, make subclasses implement the required methods, and use the ready-made abstract classes in collections.abc.
  3. Build objects out of other objects, pass work on to them, and decide when a has-a relationship fits better than an is-a relationship.
    • Build classes by composition and delegation
      Give a class other objects as attributes, delegate work to them, and keep the parts replaceable.
    • Decide between inheritance and composition
      Apply the is-a and has-a tests, recognize the costs of inheriting from a class you only want to reuse, and pick the structure that keeps classes easy to change.
  4. Implement special methods so your objects print clearly, compare and hash correctly, work with operators, and behave like containers or functions.
    • Represent and compare objects
      Write __repr__ and __str__ for clear output, define equality with __eq__, and keep __hash__ consistent with it.
    • Support comparison and arithmetic operators
      Implement ordering comparisons, arithmetic and reflected operators, and return NotImplemented for types your class does not handle.
    • Make objects work like containers and functions
      Implement __len__, __getitem__, __setitem__, __contains__, __iter__, __bool__ and __call__ so objects work with len(), indexing, in, loops, if tests and call syntax.
  5. Use properties to compute attributes, validate assignments and keep a class's public interface stable, and follow Python's conventions for internal names.
    • Create computed and read-only attributes with @property
      Turn methods into attributes with @property, keep computed values up to date, and make attributes read-only.
    • Validate data with setters and protect internal state
      Write property setters that check new values, keep objects valid from the moment they are created, and use underscores and name mangling to mark internal attributes.
  6. Generate the setup, display and comparison code of data-holding classes with @dataclass, choose defaults safely, and configure immutability, ordering, keyword-only fields and inheritance.
    • Define dataclasses with fields, defaults and validation
      Declare fields with type annotations, give them safe defaults, and add validation and derived values in __post_init__.
    • Configure frozen, ordered, keyword-only and inherited dataclasses
      Use the dataclass options for immutability, hashing, ordering, keyword-only fields and slots, combine dataclasses through inheritance, and choose between a dataclass and other ways to hold data.

Python Classes study guide

6 chapters

1

Build and trace class hierarchies

Inheritance connects a specialized class to a more general one. The connection affects both the methods an object offers and the setup it needs. Follow attribute lookup through a hierarchy, extend initializers without copying them, and trace a shared base through multiple inheritance. The method resolution order gives you a concrete way to explain which implementation runs, including what a call to super() will do.

1.1 Subclasses and attribute lookup

A subclass reuses the attributes and methods of a base class, also called a parent or superclass. The class statement names the base in parentheses. A subclass can add behavior or override a method without changing the base.

Follow a method call
class Animal:
    legs = 4

    def __init__(self, name):
        self.name = name

    def describe(self):
        return f"{self.name} is an animal"

    def speak(self):
        return "..."

class Dog(Animal):
    def speak(self):
        return "Woof"

rex = Dog("Rex")

Dog has no initializer of its own, so Dog("Rex") uses Animal.__init__ to set rex.name. For rex.describe(), lookup finds no instance attribute or Dog method named describe, then finds it in Animal. The method runs on rex and returns "Rex is an animal". For rex.speak(), the definition in Dog wins, producing "Woof".

For the ordinary attributes in this example, lookup checks the instance, its class, then the bases in the method resolution order, or MRO. A missing name raises AttributeError. A property on the class takes priority over an entry of the same name in the instance dictionary; properties use a separate access mechanism.

Test the relationship

Inheritance makes an is-a claim: a dog is an animal. Code that accepts animals should also work with dogs. The relationship goes in one direction. Adding fetch() to Dog does not give that method to Animal objects.

isinstance(rex, Animal)   # True
isinstance(rex, Dog)      # True
type(rex) == Animal       # False
issubclass(Dog, Animal)   # True
issubclass(Dog, Dog)      # True

isinstance includes subclasses; an exact type comparison does not. issubclass works on classes. Both tests accept a tuple of classes, such as isinstance(value, (int, float)). A car has an engine, but a car is not an engine; holding an engine as an attribute fits that relationship.

Separate shared and individual values

rex.legs initially reads the inherited class attribute 4. Now assign rex.legs = 3: the assignment creates an attribute in rex.__dict__. Other dogs still read the shared value 4. A subclass can also shadow a class attribute: class Bird(Animal): legs = 2 gives birds their own value without changing Animal.legs.

All these classes ultimately inherit from object. Writing class Animal: and class Animal(object): has the same effect. Without custom equality, distinct plain instances compare unequal even when their stored attributes match. Their default representation includes the class and an identity-related address.

Inspect the search path

Dog.__name__ is 'Dog', and Dog.__bases__ contains just its direct base, Animal. Dog.__mro__ contains Dog, Animal, object. If Puppy inherits from Dog, its path is Puppy, Dog, Animal, object. Several subclasses can share a base, but a long chain makes the source of a method harder to follow.

Key Takeaways

  • A subclass inherits behavior and should satisfy its base class’s public promises.
  • For ordinary attributes, lookup checks the instance and then classes in MRO order.
  • An instance assignment can shadow a class attribute without changing other instances.
  • isinstance and issubclass include subclasses; exact type tests do not.
  • __bases__ shows direct bases; __mro__ shows the full search order.

1.2 Extend setup with super()

An initializer creates the instance attributes that later methods rely on. If a subclass writes its own __init__, Python uses that version. It does not also run the base initializer for you.

Give each class its own setup work
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def describe(self):
        return f"{self.owner}: {self.balance}"

class SavingsAccount(Account):
    def __init__(self, owner, balance=0, rate=0.02):
        super().__init__(owner, balance)
        self.rate = rate

    def add_interest(self):
        self.balance += self.balance * self.rate

    def describe(self):
        return super().describe() + f" at {self.rate:.0%}"

acct = SavingsAccount("Ana", 1000, 0.03)
acct.add_interest()

First, SavingsAccount.__init__ receives the new object and all three values. Its super().__init__ call runs the next initializer on that same object, setting owner and balance. Control returns to the subclass, which stores rate. Adding interest changes the balance to 1030.0; acct.describe() returns "Ana: 1030.0 at 3%".

super() returns a proxy that continues lookup after the class where the method is defined, using the actual object's MRO. In this single-inheritance example, the next class is Account. The same mechanism works in ordinary methods, as the extending describe shows.

Let inherited setup stay inherited
class CheckingAccount(Account):
    pass

class StudentAccount(Account):
    def __init__(self, owner):
        super().__init__(owner, balance=0)

CheckingAccount("Ben", 50) inherits Account.__init__ directly. StudentAccount("Dee") has a different public constructor: it accepts only the owner and supplies a fixed starting balance. A subclass's initializer can have its own parameters while passing the base the values it needs.

Diagnose skipped or repeated arguments

Leaving out the super().__init__ call in SavingsAccount creates an object with a rate but no owner or balance. Construction can finish, and add_interest() then raises AttributeError when it reads the missing balance. Calling base setup near the start also lets the subclass use those initialized attributes safely.

Do not pass self again in super().__init__(...). The method is already bound to the object, so super().__init__(self, owner, balance) sends one argument too many and raises TypeError. The explicit spelling super(SavingsAccount, self).__init__(owner, balance) is equivalent here and also binds the object.

Copying the base assignments into the subclass duplicates its setup rules. If Account later validates the balance, the copied code skips that validation. A named call such as Account.__init__(self, owner, balance) does run the base directly, with an explicit self, but hard-codes the path. That becomes risky when several classes share a base: a direct call can skip another class or run common setup twice.

Key Takeaways

  • A new subclass __init__ replaces inherited initialization.
  • Call super().__init__(...) to reuse base setup on the same object.
  • A method obtained through super() already receives self.
  • super() also lets ordinary overrides extend existing behavior.

1.3 Multiple inheritance and cooperative calls

A class can inherit from several bases, as in class D(B, C):. Python combines the inheritance paths into one MRO, so each class has one position in the search. Read D.__mro__ or call D.mro() to inspect it.

Trace a diamond
class A:
    def greet(self):
        return ["A"]

class B(A):
    def greet(self):
        return ["B"] + super().greet()

class C(A):
    def greet(self):
        return ["C"] + super().greet()

class D(B, C):
    def greet(self):
        return ["D"] + super().greet()

The paths through B and C meet at A, forming a diamond. The MRO is D, B, C, A, object. D().greet() enters D, then B, then C, then A. The returned result is ['D', 'B', 'C', 'A']. Inside B on a D instance, super() reaches C, even though B directly inherits from A. For a plain B instance, it reaches A.

Python's C3 algorithm preserves each base's established order as well as the listed left-to-right base order. A class precedes its bases, and every class appears once. It does not search each branch all the way down before starting the next. Reversing D's bases to C, B reverses those two classes in this diamond.

If X(Base1, Base2) and Y(Base2, Base1) are combined as bases of Z, their ordering requirements conflict. Defining Z raises TypeError; Python does not choose one inconsistent route.

Pass setup along the chain

Cooperative methods all continue the chain, and their signatures must fit together. Keyword arguments let each initializer consume its own inputs:

class Colored:
    def __init__(self, *, color, **kwargs):
        super().__init__(**kwargs)
        self.color = color

class Shaped:
    def __init__(self, *, sides, **kwargs):
        super().__init__(**kwargs)
        self.sides = sides

class Tile(Colored, Shaped):
    pass

tile = Tile(color="red", sides=4)

The * makes the named parameters keyword-only. **kwargs collects remaining keyword arguments into a dictionary and forwards them when unpacked in the call. Colored consumes color; Shaped consumes sides; object receives none. An extra size=3 reaches object.__init__ and raises TypeError.

Calling both bases by name in a diamond can run their shared ancestor twice. A method that stops calling super() can cut off later work. Cooperative calls need a chain designed to reach a final implementation.

Add one capability with a mixin
import json

class JsonMixin:
    def to_json(self):
        return json.dumps(self.__dict__)

A mixin supplies a small reusable capability and is normally listed before a main base: class JsonPoint(JsonMixin, Point): pass. With a Point that stores x and y, JsonPoint(3, 4).to_json() produces '{"x": 3, "y": 4}'. This mixin needs an instance dictionary containing JSON-compatible values. A set or custom object needs conversion or a custom encoder. Prefer small mixins without setup state; combining full classes with competing state often makes composition easier to follow.

Key Takeaways

  • The MRO preserves existing base orders and gives each class one position.
  • super() follows the actual object’s MRO, including sibling classes in a diamond.
  • Cooperative initializers consume their arguments and forward the remainder.
  • Conflicting base orders raise TypeError when the class is defined.
  • A mixin supplies one capability with clear expectations about the host object.
  • Named base calls can repeat shared ancestor setup.
2

Share interfaces across classes

A useful hierarchy lets callers ask for an operation without knowing the exact class that performs it. Overrides specialize that operation, while compatible signatures keep existing calls working. Follow calls made inside a base method, build subclass-aware alternative constructors, and use duck typing across unrelated classes. Abstract base classes add an early check when a shared interface needs required methods.

2.1 Overrides and subclass-aware constructors

An override defines a method with the same name as an inherited method. Calls on subclass instances find the new version first. The base version remains available to other subclasses and through super().

Replace or extend an operation
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def annual_pay(self):
        return self.salary * 12

class Manager(Employee):
    def __init__(self, name, salary, bonus):
        super().__init__(name, salary)
        self.bonus = bonus

    def annual_pay(self):
        return super().annual_pay() + self.bonus

Manager("Lin", 4000, 6000).annual_pay() first obtains 48000 from the base method, then adds 6000, giving 54000. This override extends the base calculation. An override with a completely new body replaces it. Calling super() keeps the base's monthly-pay rule in one place.

A base method can also call a subclass override through self. Suppose Report.render() joins self.header() and self.body() with a newline. SalesReport overrides only body() to return "Sales: 120 units". The inherited render() then combines the inherited header "REPORT" with that new body. The location of the caller's code does not fix which implementation self.body() finds.

Keep existing calls valid

An override should accept the calls the base promises and return the kind of result callers expect. Adding a new required year parameter to Manager.annual_pay breaks employee.annual_pay(). An extra optional parameter can preserve that call. Renaming a parameter can also break callers that use its old keyword name.

Python does not keep several method versions based on parameter lists. Defining area(self) and later area(self, scale) leaves only the second definition. Use scale=1 to accept both forms of call. A typo such as anual_pay creates a separate method, so callers still run the inherited annual_pay. From Python 3.12, @typing.override lets a type checker help catch such mistakes.

Special methods are overridden in the same way. An __str__ returning f"{self.name} (manager)" makes printing this manager show "Lin (manager)".

Choose what a method receives
Method kindFirst automatic argumentTypical purpose
Instance methodself, the objectWork with an object's state
Class methodcls, the class used in the callBuild an object from another input format
Static methodNoneA helper grouped with the class
class Employee:
    def __init__(self, name, salary):
        self.name, self.salary = name, salary

    @classmethod
    def from_csv(cls, line):
        name, salary = line.split(",")
        return cls(name, int(salary))

class Intern(Employee):
    def annual_pay(self):
        return self.salary * 6

Intern.from_csv("Sam,1500") receives Intern as cls and returns an Intern; its annual pay is 9000. Hard-coding Employee(...) would return the wrong class. The selected class's initializer must accept the arguments supplied. @staticmethod supplies neither self nor cls.

An override that disables a promised operation signals a design problem. If callers expect every bird to fly, a penguin subclass that raises in fly() cannot meet that promise; give the flying capability its own suitable home.

Key Takeaways

  • An override may replace behavior or extend it with super().
  • Calls through self use the actual object’s overrides, even inside base code.
  • Compatible overrides preserve accepted calls and expected results.
  • A class method receives cls; using cls(...) supports inherited alternative constructors.
  • Python keeps the last definition of a method name.

2.2 Polymorphism and duck typing

Polymorphism lets one operation work across different kinds of object. Each object supplies its own response. The caller asks for the operation, and method lookup selects the implementation.

Let each shape calculate its area
import math

class Shape:
    def area(self):
        raise NotImplementedError

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w, self.h = w, h

    def area(self):
        return self.w * self.h

class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return math.pi * self.r ** 2

shapes = [Rectangle(3, 4), Circle(1)]
total = sum(shape.area() for shape in shapes)

The rectangle contributes 12 square units and the circle contributes math.pi, making the total approximately 15.14 square units. The loop needs no branch for rectangles or circles. Adding a triangle with a suitable area() method does not require changing the loop.

A chain of if type(shape) == Rectangle tests moves every class's work into the caller. It also rejects subclasses in an exact-type branch. Polymorphic calls let the class own the behavior that depends on its data.

Share an operation without sharing a base

Duck typing relies on the operations an object supports. A separately defined Square with a callable area() returning a compatible numeric result can join the list without inheriting from Shape. Matching the name alone is insufficient: the signature and result must suit the caller too.

Python uses the same approach widely. len accepts built-in collections and classes with __len__. Loops accept iterable objects. A file-like target for print(..., file=target) provides a suitable write method. Even + has type-dependent behavior: 2 + 3 is 5, "ab" + "cd" is "abcd", and [1] + [2] is [1, 2].

Catch the failure you intend to handle

EAFP, “easier to ask forgiveness than permission,” attempts an operation and handles a suitable exception. LBYL, “look before you leap,” checks first, for example with hasattr. A broad exception handler can hide a bug inside a method. To handle a missing area attribute while letting errors from its body propagate, isolate the lookup:

def read_area(obj):
    try:
        method = obj.area
    except AttributeError:
        raise TypeError("an area method is required")
    else:
        return method()

An AttributeError raised by method() is outside this handler. A present but noncallable area still fails when called. Checking an attribute's existence alone does not establish its full behavior.

Type checks remain useful at input boundaries or when the accepted type changes an operation's meaning, such as an ID accepted as an integer or a string. Use isinstance when subclasses should count.

Shape above can be instantiated. A subclass that omits area can also be instantiated and fails only when the inherited method raises NotImplementedError. An abstract base class can move that failure to object creation. Keep this exception distinct from NotImplemented, the return value operator methods use to decline an operand type; it is not an exception to raise.

Key Takeaways

  • Polymorphic callers use a shared operation while each class supplies its behavior.
  • Duck typing needs compatible operations, without requiring a shared base.
  • Keep exception handlers narrow so bugs inside a called method remain visible.
  • NotImplementedError is raised; operator methods return NotImplemented.

2.3 Required methods and abstract base classes

An abstract base class, or ABC, names methods its concrete subclasses must provide. It can also share ordinary working methods. Python checks whether abstract methods remain when an object is created.

Require one step and share the rest
from abc import ABC, abstractmethod

class Exporter(ABC):
    @abstractmethod
    def format_row(self, row):
        ...

    def export(self, rows):
        return "\n".join(self.format_row(row) for row in rows)

class CsvExporter(Exporter):
    def format_row(self, row):
        return ",".join(str(value) for value in row)

CsvExporter().export([(1, "kg"), (2, "m")]) returns "1,kg\n2,m". The inherited export supplies the shared loop and calls the concrete object's format_row implementation. Exporter() raises TypeError because the required method is still abstract. A subclass declared with pass has the same restriction until it implements that method.

The @ lines are decorators: each passes the following definition to a function that adjusts it. ABC supplies the abstract-class machinery; @abstractmethod marks a requirement. A regular method that only raises NotImplementedError lacks this instantiation check.

An ABC may define __init__ and ordinary methods, just like another base class. Even an abstract method may have a usable body; a subclass must still provide a concrete override, which can call that body through super().

Mark a property or class method abstract
class Measure(ABC):
    @property
    @abstractmethod
    def unit(self):
        ...

class Mass(Measure):
    @property
    def unit(self):
        return "kg"

Mass().unit is "kg". Measure() fails at construction. Keep @abstractmethod closest to the function, underneath @property, @classmethod, or @staticmethod. The older combined decorators such as abstractproperty are deprecated.

Use the standard collection interfaces

collections.abc supplies Iterable, Sized, Container, Sequence, Mapping, MutableMapping, Callable, and Hashable. These names describe familiar interfaces. For example, a list is a Sequence and a dictionary is a Mapping.

from collections.abc import Sequence

class Playlist(Sequence):
    def __init__(self, songs):
        self._songs = list(songs)

    def __getitem__(self, index):
        return self._songs[index]

    def __len__(self):
        return len(self._songs)

By implementing these two abstract methods, Playlist gains iteration, membership, reverse iteration, index, and count. For Playlist(["Intro", "Theme", "Intro"]), count("Intro") returns 2 and index("Theme") returns 1.

Some simple ABCs recognize suitable methods without inheritance: a class with __len__ can be recognized as Sized. Merely defining the methods of a sequence does not make a class a recognized Sequence. Virtual registration, such as Sequence.register(MyClass), makes type checks recognize the class, but supplies no methods and checks no abstract requirements.

Use an ABC when missing methods should be caught early or shared implementations are useful. An ABC does not verify that an override's signature, return value, or meaning is correct; subclasses must still honor the interface. Plain duck typing can be enough for a small group of cooperating classes.

Key Takeaways

  • ABC and @abstractmethod prevent instantiation while required methods remain abstract.
  • An ABC can combine required operations with shared working methods.
  • Stack @abstractmethod closest to the function.
  • A Sequence subclass implements __len__ and __getitem__ to gain collection helpers.
  • Virtual registration affects recognition without adding methods or enforcing requirements.
  • Implementing a method name does not prove its behavior satisfies the contract.
3

Build classes from replaceable parts

Classes can cooperate by holding and calling other objects. This gives a class a focused public interface while its parts handle their own work. Build a composed object, forward requests explicitly, and decide which parts should be supplied by callers. Then compare that design with inheritance, paying attention to unwanted inherited methods and the ways built-in classes can bypass an override.

3.1 Composition and delegated work

Composition builds an object out of other objects held as attributes. It expresses a has-a relationship: an order has line items, and a car has an engine. Each part owns a useful piece of behavior.

Let parts handle their own calculations
class LineItem:
    def __init__(self, product, price, qty):
        self.product = product
        self.price = price
        self.qty = qty

    def subtotal(self):
        return self.price * self.qty

class Order:
    def __init__(self):
        self.items = []

    def add(self, item):
        self.items.append(item)

    def total(self):
        return sum(item.subtotal() for item in self.items)

order = Order()
order.add(LineItem("pen", 1.5, 4))
order.add(LineItem("notebook", 3.25, 2))

Order.total() asks each line item for a subtotal. The pens contribute 6.0 and the notebooks 6.5, so the total is 12.5. The order combines the results; it does not repeat the multiplication rule. Prices are plain amounts in one shared unit of money.

Passing a request to a part is delegation. It may be as small as one forwarding method:

class Car:
    def __init__(self, engine):
        self._engine = engine

    def start(self):
        return self._engine.start()

A caller uses car.start() without reaching through to car._engine.start(). The outer class controls its public interface while the engine supplies the start behavior.

Supply parts from outside

Constructing Car(ElectricMotor()) works if that motor has a suitable start() method. A different engine can work through the same method. This is duck typing applied to composed parts: no exact engine type check is needed.

Passing an engine into __init__ also makes the car easier to test. A small stand-in can return a fixed result or record whether start() was called. Testing the car then does not require a real engine connection. Creating the engine inside Car would tie the car to that specific construction choice.

Parts can vary per instance and can be replaced while the program runs. One car may hold a different engine from another. A class can also hold several parts of the same kind, as the order holds several line items. Inheritance chooses bases at class definition and gives every instance that class's inherited interface.

Keep ownership clear

A whole may create parts that belong only to it. Other parts already exist and are shared: a team can refer to players who also belong to another team. The shared-reference case is often called aggregation. Both designs use object attributes in Python; ownership and lifetime expectations distinguish them. The order example receives its line items from the caller, so ownership is a design choice rather than something Python enforces.

Scattering order.items.append(...) or long paths such as car.engine.fuel_pump.pressure across callers exposes the inner structure. An outer method like add(item) gives one place to add checks or change storage later.

Automatic forwarding is possible with __getattr__, which runs only after normal attribute lookup fails. Returning getattr(self._engine, name) there forwards unknown names. It also makes the car's public operations harder to see and may expose unintended engine behavior. Explicit forwarding methods show exactly what the outer object promises.

Key Takeaways

  • Composition stores collaborating objects as parts.
  • Delegation forwards an outer operation to a part.
  • Constructor-supplied parts support replacement and simple test stand-ins.
  • Public outer methods reduce callers’ dependence on internal structure.

3.2 Choose the relationship before reusing code

Code reuse alone is a weak reason to inherit. A subclass receives the base's whole public interface and makes a claim about what kind of object it is. Composition lets the outer class choose a smaller set of operations.

Compare the public promises
QuestionInheritanceComposition
What relationship does it express?A specialized object is a base-type objectAn object has or uses parts
What interface is exposed?Inherited public methods plus additionsThe outer class's chosen methods
How can behavior vary?Through subclass definitions and overridesThrough the objects supplied as parts
What does reuse depend on?The base interface and often its internal call structureThe parts' public operations

A savings account is an account if it can honor account operations. A car has an engine. Inheriting Car from Engine just to obtain start() also makes isinstance(car, Engine) true and exposes every inherited engine operation on the car.

Build a stack with a limited interface
class ListStack(list):
    def push(self, item):
        self.append(item)

A stack removes the most recently added item first. ListStack supplies push, but callers can also use sort, insert, reverse, and indexed assignment inherited from list. Those operations allow them to rearrange storage outside the intended stack operations.

class Stack:
    def __init__(self):
        self._items = []

    def push(self, item):
        self._items.append(item)

    def pop(self):
        return self._items.pop()

    def __len__(self):
        return len(self._items)

Pushing 1, 2, and 3, then calling pop(), returns 3 and leaves a length of 2. The outer object offers only the selected operations. Its internal list can later change without requiring callers to change their stack calls. The underscore marks storage as internal; it does not technically block direct access.

Do not assume built-in methods call overrides

A dict subclass might override __setitem__ to capitalize keys. Direct assignment such as d["a"] = 1 runs that override. Inherited initialization and update, however, can write directly to the dictionary's storage, leaving "b" or "c" lowercase. The fact that direct assignment works does not prove all insertion routes use it.

collections.UserDict and UserList provide wrappers designed for customization through their methods. Use them when that interface fits, or hold the underlying collection as a composed part and control the exposed operations yourself.

The fragile base class problem occurs when a subclass relies on its base's internal choices. A change in which methods the base calls can invalidate the override's assumptions. An outer class that uses a part's documented public operations has fewer such dependencies.

Apply the is-a test to behavior

Ask whether the specialized class can be used wherever the base is expected, whether every public base method makes sense on it, and whether it needs replaceable parts or several parts of the same kind. Composition often suits the latter needs. Inheritance remains useful for a genuine specialization, including class InsufficientFundsError(ValueError): pass, whose instances can be caught as ValueError, or test classes based on unittest.TestCase.

A drawing can combine the two designs: shapes form a shallow class hierarchy, and a drawing holds a collection of shape objects. A small mixin can add an independent capability such as JSON export.

Key Takeaways

  • Choose inheritance when the subclass can fulfill the base type’s public contract.
  • Composition lets an outer class expose only its intended operations.
  • Inherited built-in operations may bypass a subclass override.
  • UserDict and UserList support customization through their methods.
  • Depending on a base’s internal calls makes a subclass fragile.
4

Make objects work with Python syntax

Built-in syntax becomes useful for your own classes when you give it a clear meaning. Special methods connect objects to printing, equality, sets, sorting, arithmetic, containers, and function calls. Work through how Python selects these methods, how an unsupported operand gets another chance, and which rules a method must obey. The aim is behavior that callers can predict from familiar Python operations.

4.1 Readable output, equality, and safe hashes

Special methods, or dunder methods, have double underscores at both ends. Python uses them for built-in operations. Define them on the class: assigning obj.__len__ = lambda: 3 to an ordinary instance does not teach len(obj) to find it.

Give objects a useful representation

__repr__ provides precise output for developers. When practical, make it resemble a constructor call. __str__ supplies readable text for users. Both must return strings.

class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return f"{type(self).__name__}({self.x!r}, {self.y!r})"

    def __eq__(self, other):
        if not isinstance(other, Vector):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)

repr(Vector(2, 3)) is 'Vector(2, 3)'. The !r formats each value using its own representation, and the class name follows the actual type. Because this class has no __str__, str and print fall back to __repr__. A custom __str__ alone would not replace repr. Containers also display the repr of each item, so a list shows [Vector(2, 3)].

Compare values without losing identity
a = Vector(1, 1)
b = Vector(1, 1)
a == b    # True
a is b    # False

== asks about the equality rule; is asks whether two names refer to the same object. The vectors have matching coordinates but separate identities. Without an equality override, plain objects use identity-based equality. Use is None to check for the particular singleton None.

For a supported vector, __eq__ compares the coordinate tuples. For an unsupported type, it returns NotImplemented. That gives Python a chance to use the other object's equality method. If neither object handles equality, Python falls back to identity. Vector(2, 3) == (2, 3) is therefore False. For supported Boolean equality results, inherited != negates the result.

Reading other.x without checking compatibility can make vector == 5 fail with AttributeError. Return the special value for an unsupported comparison; do not raise NotImplemented or return the exception class NotImplementedError.

Keep hashing consistent with equality

Sets and dictionaries use hashes to locate entries, then equality to distinguish candidates. Equal objects must have equal hashes. Unequal objects may share a hash; equality resolves that collision.

Defining __eq__ without __hash__ sets the class's hash method to None. The mutable Vector above is unhashable, so putting it in a set raises TypeError.

For a design whose compared coordinates remain fixed, a matching implementation is def __hash__(self): return hash((self.x, self.y)). Two equal fixed vectors then occupy one set entry. A hash must stay stable during the object's lifetime. Adding that method to a freely mutable vector is unsafe: changing a coordinate can change its hash after insertion, so a set or dictionary may fail to find the stored object. Keep mutable value objects unhashable, or redesign their compared state to stay fixed.

Key Takeaways

  • Define special methods on the class for built-in syntax to find them.
  • __repr__ supports precise display; __str__ supports user-readable display.
  • == uses equality behavior; is tests identity.
  • Return NotImplemented when an equality method cannot handle the other type.
  • Equal hashable objects must have equal, stable hashes.
  • An equality override without a hash override makes instances unhashable.

4.2 Comparison and arithmetic methods

Operators are method calls with rules for trying both operands. Give an operator a meaning that suits the type, such as vector addition or duration scaling. A clearly named method is easier to understand when the action has no natural operator meaning.

Order structured values

The ordering methods are __lt__ for <, __le__ for <=, __gt__ for >, and __ge__ for >=. Sorting uses <, so a suitable __lt__ is enough to sort objects. A comparison can also try the mirrored method on the other operand: a > b can use b.__lt__(a).

from functools import total_ordering

@total_ordering
class Version:
    def __init__(self, major, minor):
        self.major, self.minor = major, minor

    def __eq__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return (self.major, self.minor) == (other.major, other.minor)

    def __lt__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return (self.major, self.minor) < (other.major, other.minor)

total_ordering supplies missing order comparisons from equality and one ordering method. Numeric tuple comparison puts version 1.9 before 1.10, then 2.0. Comparing the strings "1.10" and "1.9" orders characters and gives the wrong version order. For an unsupported operand, NotImplemented lets Python try its partner method; unresolved ordering raises TypeError.

Support both multiplication directions
class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __add__(self, other):
        if not isinstance(other, Vector):
            return NotImplemented
        return Vector(self.x + other.x, self.y + other.y)

    def __mul__(self, factor):
        if not isinstance(factor, (int, float)):
            return NotImplemented
        return Vector(self.x * factor, self.y * factor)

    __rmul__ = __mul__

Adding Vector(2, 3) and Vector(1, -1) creates coordinates (3, 2). Multiplying Vector(2, 3) by 2 creates (4, 6). Both operations leave the original operands unchanged. For 2 * v, the integer cannot handle the vector, so Python tries the vector's reflected multiplication, __rmul__. Sharing the implementation works here because scalar multiplication has the same meaning in either direction. Reflected subtraction would need to preserve the reversed operand order.

Other arithmetic hooks include __sub__, __truediv__, __floordiv__, __mod__, and __pow__. Returning NotImplemented for an unsupported type allows fallback; if neither operand handles the operation, Python raises TypeError.

Check the starting value and rebinding

sum(vectors) starts with integer 0, so its first step is 0 + vectors[0]. Without suitable __radd__, that fails. sum(vectors, Vector(0, 0)) supplies a vector starting value.

+= first tries __iadd__. If it is absent, addition can produce a new object and rebind the left name. A mutable class can implement __iadd__ by changing itself and returning self; omitting the return rebinds the left name to None. Other names still point to the mutated object.

Unary -v uses __neg__; abs(v) uses __abs__. With return math.hypot(self.x, self.y), abs(Vector(3, 4)) gives 5.0.

Key Takeaways

  • Sorting uses <; total_ordering fills comparisons from equality and one ordering method.
  • Reflected arithmetic supports the right operand when the left cannot handle the operation.
  • Return NotImplemented for unsupported operand types.
  • Supply a matching start value when sum cannot add integer zero to the first object.
  • An in-place method must return the object that the left name should receive.

4.3 Containers, truth values, and callable objects

A class can support familiar Python syntax by implementing the corresponding operations. Choose the methods that match its public purpose; it does not need every available hook.

Delegate container operations to stored data
class Deck:
    ranks = [str(n) for n in range(2, 11)] + list("JQKA")
    suits = ["spades", "hearts", "diamonds", "clubs"]

    def __init__(self):
        self._cards = [(r, s) for s in self.suits for r in self.ranks]

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, index):
        return self._cards[index]

len(deck) calls the class's __len__; deck[index] calls __getitem__. For a new deck, the length is 52, the first item is ('2', 'spades'), and the last is ('A', 'clubs'). deck[:3] sends a slice object to __getitem__, and the stored list handles it. random.choice(deck) can use the length and indexing methods too.

SyntaxSpecial method
obj[key] = value__setitem__
del obj[key]__delitem__
item in obj__contains__
for item in obj__iter__

A simple iterator implementation returns iter(self._cards). It must return an iterator, not the stored list itself. Without __iter__, Python can fall back to positional __getitem__ calls starting at zero and stopping at IndexError. Without __contains__, membership can scan the iterable items and compare them with ==. A custom membership method is useful when a set lookup would be faster.

Indexing can use other keys. grid[1, 2] passes the tuple (1, 2), so a grid can store cells in a dictionary. Sequence positions outside the range should raise IndexError; missing mapping keys should raise KeyError. These exceptions tell callers what failed and let protocol fallbacks behave correctly.

Give truth tests a clear meaning

if obj: first uses __bool__, which must return a Boolean. Without it, Python uses __len__: zero is false and a positive length is true. An object with neither method is truthy.

An empty container can therefore be a real object and still be falsy. To ask whether a deck variable holds an object instead of None, write deck is not None. A __len__ result must be a nonnegative integer. Returning 2.5 raises TypeError, and returning -1 raises ValueError.

Keep state in an object that can be called
class Multiplier:
    def __init__(self, factor):
        self.factor = factor

    def __call__(self, value):
        return value * self.factor

triple = Multiplier(3)

triple(7) calls __call__ and returns 21; callable(triple) is True. A callable object can retain settings or count calls between uses.

Collection ABCs can supply the surrounding methods. A Sequence subclass implements __len__ and __getitem__. A MutableMapping subclass implements __getitem__, __setitem__, __delitem__, __iter__, and __len__; inherited methods then include get, pop, update, and setdefault. Each primitive must obey the interface's expected meaning.

Key Takeaways

  • Container syntax calls matching special methods on the class.
  • Return an iterator from __iter__; use IndexError to end positional iteration.
  • Truth tests use __bool__, then __len__, then a default true value.
  • Use is not None when an empty object must still count as present.
  • __call__ lets an instance keep state while acting like a function.
  • Collection ABCs build useful methods from a smaller required set.
5

Compute and validate attributes

Properties let callers keep simple attribute syntax while a class computes or checks the value behind it. Use a getter for a value derived from current state, and a setter when assignment must preserve a rule. Follow validation from construction through later changes, avoid recursive access, and distinguish a recomputed property from a cached value. Underscore conventions help keep the public interface separate from storage.

5.1 Computed and read-only properties

A property runs a method through attribute access. A caller writes rectangle.area, and the class decides how to obtain the result.

Compute from the current data
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @property
    def area(self):
        return self.width * self.height

r = Rectangle(3, 4)

The decorator @property turns the following method into a managed attribute. The getter takes only self. Reading r.area calls it and returns 12. After r.width = 5, the next read gives 20, because the getter multiplies the current values.

Storing self.area = width * height once in __init__ gives a different design. After changing width, that stored area still holds the old number unless some code updates it.

Separate reading from calling

r.area() first reads the property, then tries to call its result. Here the result is an integer, so the call raises TypeError.

A property with no setter is read-only through that public name. Assigning r.area = 30 raises AttributeError. The dimensions can still change, and the next area read reflects them. A read-only property does not make the entire object immutable.

Keep the storage name distinct

A property that exposes stored data normally uses a separate internal name:

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

The getter reads _radius. Returning self.radius inside the radius getter would call the same getter again, repeating until RecursionError. Properties take precedence over a same-named entry in an ordinary instance dictionary, so adding a dictionary entry named radius is not a way to replace the getter.

Properties support gradual interface changes. A class can begin with plain obj.radius storage and later add validation behind a property without requiring callers to adopt separate get_radius and set_radius methods.

Choose whether to cache a result

functools.cached_property computes a value on first access and stores the result on the instance. Later reads reuse it. This suits expensive calculations whose inputs stay unchanged.

If a cached total sums a stored list, appending to the list does not refresh that total. An ordinary property recomputes on every read. Pick caching only when stale results are prevented or managed by the design. A standard cached_property also needs a writable instance dictionary, so it does not fit a slotted object that lacks one.

Callers expect attribute reads to be quick and unsurprising. Keep a property focused on obtaining an attribute value. Work such as reading a file or contacting a service fits a clearly named method, where the caller can see that an operation is taking place.

Key Takeaways

  • A property getter runs through attribute syntax without parentheses.
  • A computed property uses current input values on each read.
  • A property without a setter is read-only through its public name.
  • Use a different storage name inside the getter to avoid recursion.
  • A cached property reuses its first result and can become stale if inputs change.

5.2 Setters, valid state, and internal names

A setter controls assignment to a property. It can reject an invalid value before changing storage, so the object keeps its existing valid state. Construction should use the same validation path as later updates.

Validate at both entry points
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("temperature below absolute zero")
        self._celsius = value

    @property
    def kelvin(self):
        return self._celsius + 273.15

The initializer assigns to self.celsius, which runs the setter. Temperature(-300) therefore raises ValueError. Directly writing _celsius in the initializer would bypass the check. For Temperature(25), kelvin gives 298.15. Assigning t.celsius = 100 changes the next reading to 373.15.

The setter checks before storing. If a later assignment is rejected, the previous temperature remains intact. This protects an invariant, a rule the object's state should continue to satisfy. Validation must still cover the kinds of values the public interface accepts; an annotation or underscore alone adds no validation.

Match the property name

Use @celsius.setter above def celsius(self, value). Naming the decorated method set_celsius binds the new property to that other name, leaving celsius read-only. Assigning t.celsius then raises AttributeError. Writing self.celsius = value inside its own setter would recurse; store _celsius after the check.

A property may also have a deleter, defined using @name.deleter, which handles del obj.name. Many attributes do not need deletion behavior.

Choose an update method for linked values

Some rules involve more than one attribute. An account can expose a read-only balance while deposit and withdraw check changes to _balance. A withdrawal of 50 from a balance of 30 raises ValueError for insufficient funds. A method can validate several proposed values together before committing a combined update. Separate setters can otherwise leave a temporary invalid combination or reject an update whose final state would be valid.

Understand what underscores do

A single leading underscore marks a name such as _balance as internal by convention. Python still allows access. Callers should use the public interface so storage can change without breaking their code.

Two leading underscores without two trailing underscores trigger name mangling inside a class. self.__id in Base becomes _Base__id; the same spelling inside Child becomes _Child__id.

class Base:
    def __init__(self):
        self.__id = 1

class Child(Base):
    def __init__(self):
        super().__init__()
        self.__id = 2

Child().__dict__ contains both '_Base__id': 1 and '_Child__id': 2. The subclass does not overwrite the base's field accidentally. Its own self.__id also does not access the base's field. The transformed name can still be used from outside, so mangling prevents name collisions, not unauthorized access. Use a single underscore unless a subclass collision is the problem you need to solve.

Key Takeaways

  • A setter validates assignment and stores under a different internal name.
  • Assign through the property in __init__ to apply the same checks during construction.
  • Check before changing storage so rejected updates preserve the old valid value.
  • Use one method to validate a change involving several linked attributes.
  • A leading underscore marks an internal name by convention.
  • Name mangling separates base and subclass names without providing access security.
6

Use dataclasses for named records

Data-holding classes often repeat the same setup, display, and comparison code. Dataclasses generate that work from annotated fields while leaving room for methods and validation. Define independent mutable defaults, decide which fields belong in generated methods, and choose options for fixed records, ordering, and keyword-only calls. Inheritance needs special care because field order and base initialization affect the generated constructor.

6.1 Fields, defaults, and post-initialization

@dataclass generates common methods from annotated fields. By default these include __init__, __repr__, and __eq__. An annotation names the intended type; it does not enforce that type at run time.

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float = 0.0

Point(1.5) displays as Point(x=1.5, y=0.0). It compares equal to Point(1.5, 0.0). Generated equality compares participating fields in order and requires the same concrete class: the tuple (1.5, 0.0) is not equal to this point. Point("a", "b") is still accepted because no validation rejects those arguments.

Identify fields correctly

An ordinary declaration such as x = 0 has no annotation, so it is a class attribute instead of a dataclass field. It contributes no constructor parameter or generated comparison value. To make a shared class variable explicit, annotate it with typing.ClassVar, such as count: ClassVar[int] = 0; dataclasses exclude it from fields.

Fields become constructor parameters in definition order. Required positional fields must precede fields with defaults. Writing x: float = 0.0 before required y: float raises TypeError during class creation.

Give each instance fresh mutable data
from dataclasses import dataclass, field

@dataclass
class Notebook:
    title: str
    tags: list[str] = field(default_factory=list)

The factory is the callable list, not the result list(). The generated initializer calls it whenever a new notebook needs a default, giving each notebook its own list. Notebook("A").tags and Notebook("B").tags are separate objects.

Using tags: list = [] is rejected with ValueError. Lists, dictionaries, and sets cannot serve as direct defaults; since Python 3.11, the rejection covers unhashable defaults generally. A factory avoids sharing a mutable default between instances.

Configure generated methods
Field optionEffect
init=FalseOmit the field from constructor arguments
repr=FalseOmit it from generated representation
compare=FalseOmit it from generated equality and ordering

Hiding a value from repr changes display only; it does not prevent access to the attribute.

@dataclass
class Rectangle:
    width: float
    height: float
    area: float = field(init=False)

    def __post_init__(self):
        if self.width <= 0 or self.height <= 0:
            raise ValueError("sides must be positive")
        self.area = self.width * self.height

The generated initializer stores width and height, then calls __post_init__. Rectangle(3, 4) sets area to 12, while Rectangle(0, 4) raises ValueError. Because area is stored once, later width changes leave it stale. A computed property suits a derived value that must follow mutable inputs.

A dataclass is still an ordinary class: add methods and properties as needed. A user-defined __init__, __repr__, or __eq__ is kept instead of generating that method. If you supply your own initializer, it must arrange any post-initialization call you need.

The helpers asdict(p) and astuple(p) return field-based dictionary and tuple representations. replace(p, y=2.0) constructs a new point with the requested change, leaving p unchanged.

Key Takeaways

  • Annotated fields drive generated setup, representation, and equality.
  • Annotations describe intended types without validating values at run time.
  • default_factory supplies a fresh mutable default when each instance needs one.
  • field options choose which generated methods include a field.
  • __post_init__ follows generated initialization and can validate or derive values.
  • Stored derived values can become stale when their inputs change.

6.2 Configure fixed records, ordering, and inheritance

Dataclass options adjust generated behavior. Choose them to match how a record will be used: as a mutable holder, a stable dictionary key, an ordered record, or a class with a tightly defined set of attributes.

Freeze assignments and check hashability

@dataclass(frozen=True) blocks ordinary field assignment with FrozenInstanceError, a subclass of AttributeError. Use replace(record, x=5) to create a modified record.

Freezing is shallow. A list stored in a frozen field can still be appended to, even though that field cannot be rebound. A generated hash also fails if a participating field is unhashable. Tuples suit sequences of fixed, hashable values.

OptionsDefault hash behavior
eq=True, frozen=FalseInstances are unhashable
eq=True, frozen=TrueA field-based hash is generated
eq=FalseThe inherited hash behavior is retained

Two frozen pixels with equal hashable coordinates occupy one set entry. unsafe_hash=True can force generation for a mutable dataclass, but changing equality-relevant data still risks breaking dictionary and set lookup.

Order by field priority

order=True generates <, <=, >, and >=, comparing participating fields in definition order like a tuple. A Version with fields major then minor puts 1.9 before 1.10 before 2.0. The first unequal field decides. field(compare=False) removes a field from both equality and ordering. The generated comparisons require the same concrete type; ordering against a tuple raises TypeError.

Make calls and storage explicit

@dataclass(kw_only=True) makes that class's fields keyword-only. A configuration with host and default port=8080 is created as Config(host="example.org"). Positional field arguments raise TypeError. To limit the effect, use field(kw_only=True) on one field or place _: KW_ONLY before the keyword-only fields.

slots=True generates slots for fields and can reduce instance memory. With no base-provided instance dictionary, an extra attribute such as p.xx = 3 raises AttributeError. A normal base can supply a __dict__, so a slotted subclass of it can still accept extra attributes. On Python 3.12 and 3.13, zero-argument super() in a slotted dataclass method raises TypeError; use super(ClassName, self). Python 3.14 fixes that behavior.

Read the combined constructor
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    email: str = ""

@dataclass(kw_only=True)
class Student(Person):
    student_id: int

Base fields come first, followed by subclass fields. Here Student("Ana", student_id=42) works: name and email retain the base's calling rules, and the required ID is keyword-only. Without that option, required student_id would follow default email, raising TypeError. Giving the ID a default is another fix when that default makes sense.

A generated dataclass initializer initializes inherited dataclass fields itself. It does not call an ordinary, non-dataclass base's __init__. If that base needs setup, call super().__init__(...) from __post_init__, using the explicit super(ClassName, self) spelling for slotted classes on Python 3.12 or 3.13.

Choose a dataclass for named data with useful behavior. A plain class suits more specialized setup; NamedTuple suits an immutable record that should support tuple indexing and unpacking; a dictionary suits keys determined at run time.

Key Takeaways

  • Frozen dataclasses block rebinding but do not freeze mutable objects held in fields.
  • A generated hash works only when its participating values are hashable and stable.
  • Ordering compares participating fields in their definition order.
  • Keyword-only subclass fields can avoid inherited default-order conflicts.
  • Slots block extra attributes only when instances have no inherited dictionary.
  • Generated setup includes dataclass base fields but skips ordinary base initializers.
  • Choose the record structure according to the interface callers need.

Python Classes examples

6 Walkthroughs

1

Follow an object through its hierarchy

15 steps
Trace inherited lookup and setup, then follow cooperative calls through a diamond.
  1. 1
    IntroductionFind the next implementation

    An inherited method is not copied into each new object. Python finds it through the object's class hierarchy, then runs it on that object.

    We will build a small record hierarchy, follow setup and ordinary method calls, and then combine two branches. Keep two questions separate: where is the method found, and which object is self? The first can change along a chain; the second stays the same.

  2. 2
    ExampleGive a record a specialized label
    class Record:
        kind = "record"
    
        def __init__(self, name):
            self.name = name
    
        def label(self):
            return f"{self.kind}: {self.name}"
    
    class Alert(Record):
        kind = "alert"
    
    a = Alert("heat")
    

    Alert inherits __init__ and label. Creating a stores its own name, "heat". The class attribute kind is specialized without changing Record.kind, so the base can still describe ordinary records.

  3. 3
    ExplanationTrace the label read

    a.label() finds no label on the instance or in Alert, then finds Record.label. Inside it, self is still the alert.

    self.kind finds Alert.kind, and self.name finds the instance value. The returned string is "alert: heat". For ordinary attributes, search the instance before the classes in MRO order. A class property has priority over a same-named instance dictionary entry.

  4. 4
    ChallengeChange one alert

    Continue with the alert above. What are the two strings after these lines?

    a.kind = "urgent"
    b = Alert("smoke")
    (a.label(), b.label())
    

    ---reveal---

    The tuple is ('urgent: heat', 'alert: smoke'). Assignment gives a its own shadowing kind; b still reads the subclass value. isinstance(a, Record) remains true. Changing the instance value does not change its class or the inherited relationship.

  5. 5
    ExampleAdd subclass setup
    class TimedAlert(Alert):
        def __init__(self, name, minutes):
            super().__init__(name)
            self.minutes = minutes
    

    This subclass takes an extra input. Its initializer replaces the inherited one, so it must arrange the setup that creates name. The super() call reaches the inherited initializer on the same object. After that call, subclass code can safely use self.name and add its own minutes attribute.

  6. 6
    TipPass values, without a second self

    A method obtained through super() is already bound to the instance. Write super().__init__(name), passing only the explicit input.

    Copying the base's assignments would miss later changes to its setup. Calling Record.__init__(self, name) directly runs that named class, but fixes a path that may skip another class after multiple inheritance is introduced. Cooperative super() calls can follow the hierarchy as it changes.

  7. 7
    ChallengeExtend an ordinary method

    Add this method to TimedAlert. What does TimedAlert("frost", 12).label() return?

    def label(self):
        return super().label() + f" ({self.minutes} min)"
    

    ---reveal---

    It returns "alert: frost (12 min)". Setup stores name and minutes; inherited lookup gives kind the alert value. super().label() supplies the shared label first, and the override appends its own text. super() supports ordinary methods as well as initializers.

  8. 8
    ExampleCreate two branches
    class End:
        def steps(self):
            return ["end"]
    
    class Audit(End):
        def steps(self):
            return ["audit"] + super().steps()
    
    class Stamp(End):
        def steps(self):
            return ["stamp"] + super().steps()
    
    class Event(Audit, Stamp):
        pass
    

    Both branches reach End, forming a diamond. Each branch adds its label and continues. End supplies the final implementation that stops this method chain.

  9. 9
    ExplanationFollow the actual object’s MRO

    Event.__mro__ is Event, Audit, Stamp, End, object. Therefore Event().steps() returns ['audit', 'stamp', 'end'].

    The surprising call is inside Audit: on an Event, its super() reaches Stamp, not its direct base End. On a plain Audit, the next class is End. The MRO preserves base-order requirements and lists each class once; it does not finish the first branch before considering the second.

  10. 10
    ChallengeStop forwarding

    In a new version of the previous diamond, replace only Stamp.steps with this method. What does Event().steps() return?

    def steps(self):
        return ["stamp"]
    

    ---reveal---

    It returns ['audit', 'stamp']. Audit still forwards to Stamp, but the new method never asks the next implementation to run. End.steps is therefore skipped. A unique MRO does not itself execute every method; each cooperative method must continue the chain.

  11. 11
    ExplanationConsume keyword inputs along the chain
    class Colored:
        def __init__(self, *, color, **kwargs):
            super().__init__(**kwargs)
            self.color = color
    
    class Sized:
        def __init__(self, *, width, **kwargs):
            super().__init__(**kwargs)
            self.width = width
    

    For class Label(Colored, Sized): pass, Label(color="blue", width=6) works. Each initializer consumes its named input and forwards the rest. Nothing remains when object.__init__ runs; an unused keyword would raise TypeError there.

  12. 12
    ConnectionAdd one capability with a mixin

    A mixin is a small class combined with a main base to add a capability. A mixin placed before the main base can supply to_json() by calling json.dumps(self.__dict__).

    That implementation assumes an instance dictionary and values the JSON encoder supports. A set-valued attribute needs conversion or another encoder. Keeping mixins focused and light on setup state makes their interactions easier to reason about than combining several full stateful bases.

  13. 13
    TipCheck ordering before tracing calls

    Inspect ClassName.__mro__ when several bases interact. The direct bases in __bases__ do not show the whole search path.

    If one base requires A before B and another requires B before A, a combined class can have no valid MRO; defining it raises TypeError. In a valid diamond, direct named calls to both branches can still run shared setup twice. The MRO coordinates lookup only when the methods cooperate with it.

  14. 14
    ChallengeCombine setup and lookup

    Tagged inherits from Colored and Sized above, has no initializer, and defines describe(self) to return f"{self.color}:{self.width}". A subclass WideTag(Tagged) defines its initializer as:

    def __init__(self, color):
        super().__init__(color=color, width=9)
    

    What does WideTag("green").describe() return?

    ---reveal---

    It returns "green:9". The new initializer supplies both keywords; the cooperative chain stores them on the same object. The inherited method then reads those instance attributes.

  15. 15
    RecapUse lookup and setup as separate traces

    To inspect a hierarchy, find the object's actual class and read its MRO. Resolve each ordinary attribute from the instance through that path, allowing for managed properties.

    For setup, trace every explicit initializer call and note which attributes it creates. For cooperative methods, continue only where a super() call occurs. This separates a missing attribute caused by skipped setup from a method result caused by lookup or an override.

2

Make one caller work across classes

15 steps
Use overrides, duck typing, and abstract requirements to keep a shared caller dependable.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep the caller focused on its job
  2. 2
    ExampleLet base code call an override
  3. 3
    ExampleExtend the result
  4. 4
    ChallengePreserve an existing call
  5. 5
    ExplanationConstruct the class that received the call
  6. 6
    ChallengeFind a constructor that loses the subclass
  7. 7
    ExplanationUse operations across unrelated classes
  8. 8
    TipSeparate lookup failure from a method bug
  9. 9
    ChallengeCheck the actual operation
  10. 10
    ExampleMake the requirement explicit
  11. 11
    Key InsightShare code without weakening the requirement
  12. 12
    ChallengeSeparate completeness from compatibility
  13. 13
    ConnectionUse standard collection agreements
  14. 14
    ChallengeAdd a new output class
  15. 15
    RecapCheck calls, results, and requirements
3

Design an object around its parts

11 steps
Build a small message service, delegate delivery, and choose a controlled public interface.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive each part a clear job
  2. 2
    ExampleStart with a small sender
  3. 3
    ExampleCompose the service
  4. 4
    ChallengeUse a recording part
  5. 5
    ConnectionDecide who owns the part
  6. 6
    ExplanationApply the is-a test to operations
  7. 7
    ExampleExpose a stack’s intended operations
  8. 8
    TipVerify every route through a built-in class
  9. 9
    ChallengeChoose reuse without extra operations
  10. 10
    ChallengeReplace delivery without changing callers
  11. 11
    RecapKeep the outside stable
4

Give a custom type familiar Python behavior

18 steps
Build value and container behavior step by step, including fallback, identity, and truth tests.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTranslate syntax into operations
  2. 2
    ExampleShow the values inside an object
  3. 3
    ExampleCompare coordinates
  4. 4
    Key InsightEquality changes hashing expectations
  5. 5
    ChallengeDistinguish equality from sameness
  6. 6
    ExplanationChoose a meaningful ordering
  7. 7
    ExampleCreate a new arithmetic value
  8. 8
    ExampleScale in either operand order
  9. 9
    TipInspect sum’s first operation
  10. 10
    ChallengeTrack an alias through +=
  11. 11
    ConnectionKeep operator meanings predictable
  12. 12
    ExampleWrap a sequence with two methods
  13. 13
    ExplanationLet the index object reach storage
  14. 14
    Key InsightIteration and membership have fallbacks
  15. 15
    ChallengeAn empty object is still present
  16. 16
    ExampleRetain settings in a callable instance
  17. 17
    ChallengeCombine collection and value behavior
  18. 18
    RecapRead each contract at the syntax boundary
5

Keep attributes current and valid

12 steps
Use properties for derived values and validated assignments, then trace internal names across inheritance.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate public attributes from storage
  2. 2
    ExampleCompute a perimeter on access
  3. 3
    TipUse attribute syntax for a property
  4. 4
    ConnectionCaching changes update behavior
  5. 5
    ChallengeCompare a stored value and a live read
  6. 6
    ExampleValidate through one public name
  7. 7
    ChallengePreserve the old value on failure
  8. 8
    ExplanationUpdate linked attributes together
  9. 9
    ExampleRead mangled names in their defining class
  10. 10
    TipUse the simplest internal-name convention
  11. 11
    ChallengeConnect validation with a derived value
  12. 12
    RecapTrace every route that changes state
6

Build and configure reliable dataclasses

16 steps
Define a record with independent defaults and validation, then reason about freezing, ordering, and inherited setup.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionRead a compact class as generated behavior
  2. 2
    ExampleGenerate methods from fields
  3. 3
    ExampleCreate a fresh list for each parcel
  4. 4
    ChallengeCheck default independence
  5. 5
    ExplanationChoose a field’s generated roles
  6. 6
    ExampleValidate after field assignment
  7. 7
    ConnectionCreate new records with helpers
  8. 8
    ExplanationFreeze field bindings, not everything inside
  9. 9
    ChallengeSeparate a generated hash from a usable hash
  10. 10
    ExamplePut the sorting priority first
  11. 11
    ExampleHandle inherited field defaults
  12. 12
    TipSelect keyword-only fields and slots carefully
  13. 13
    ExampleRun needed ordinary base setup
  14. 14
    ChallengeChoose a data structure for its interface
  15. 15
    ChallengeConnect replacement, order, and identity
  16. 16
    RecapInspect fields before trusting generated code

Python Classes practice questions

50 Practice Questions in 5 sets

Set 1: Use shared interfaces and replaceable parts10 Practice Questions

Question 1 of 10

A class defines save(self) and later defines save(self, path) under the same name. What happens when an instance calls save() without a path?
  1. It runs the earlier zero-argument definition.
  2. It runs both definitions in declaration order.
  3. It chooses a definition from the argument count.
  4. It raises TypeError for the missing argument.
Show answerHide answer
Answer: D
The later definition replaces the earlier binding of save in the class. Calling it without path raises TypeError because Python does not retain overloads based on parameter count. A default such as path=None could make one implementation accept both call forms.

Question 2 of 10

Why is the call placed in else here?

try:
    action = device.reset
except AttributeError:
    result = "unavailable"
else:
    result = action()
  1. To let AttributeError inside reset() propagate.
  2. To convert TypeError from reset() into text.
  3. To require reset() to return an attribute name.
  4. To retry reset() after a failed attribute lookup.
Show answerHide answer
Answer: A
Only the lookup of device.reset is inside the try. If that lookup fails, the handler records unavailability; if the method itself raises AttributeError, the call in else lets it propagate. Putting the call inside the try would blur those two failures.

Question 3 of 10

What is the result of the final expression?

class Local:
    def size(self):
        return 4

class Remote:
    def size(self, unit):
        return 6

class Special(Local):
    def size(self):
        return super().size() + 3

sum(x.size() for x in [Local(), Special(), Remote()])
  1. 10
  2. 17
  3. A TypeError is raised.
  4. An AttributeError is raised.
Show answerHide answer
Answer: C
The first two calls return 4 and 7. The third object has size, but its signature requires a unit argument, so the no-argument call raises TypeError and sum produces no result. Duck typing requires compatible calls, not just matching method names.

Question 4 of 10

After this registration, what pair describes isinstance(x, Channel) and hasattr(x, "send")?

from abc import ABC, abstractmethod

class Channel(ABC):
    @abstractmethod
    def send(self, text):
        ...

class Token:
    pass

Channel.register(Token)
x = Token()
  1. (False, False)
  2. (True, False)
  3. (True, True)
  4. (False, True)
Show answerHide answer
Answer: B
Virtual registration makes Token recognizable as a Channel, so the instance check is true. It neither copies send into Token nor enforces implementation of abstract methods. The pair (True, True) would confuse registration with ordinary inheritance of methods.

Question 5 of 10

What pair results?

from collections.abc import Sequence

class Route(Sequence):
    def __init__(self):
        self._stops = ["hill", "lake", "hill", "port"]

    def __len__(self):
        return len(self._stops)

    def __getitem__(self, i):
        return self._stops[::-1][i]

r = Route()
(r.count("hill"), r.index("port"))
  1. (2, 0)
  2. (2, 3)
  3. (1, 0)
  4. (1, 3)
Show answerHide answer
Answer: A
The inherited Sequence helpers use Route’s indexing, which exposes the stored stops in reverse order. That visible sequence is ["port", "hill", "lake", "hill"], so "hill" occurs twice and "port" has index 0. Reporting index 3 would inspect the internal list instead of the sequence interface those helpers actually use.

Question 6 of 10

A Recorder stores a writer and implements record(text) as self.writer.write(text). What relationship and action does this show?
  1. Inheritance with method replacement.
  2. Composition with automatic name mangling.
  3. Inheritance with reflected dispatch.
  4. Composition with explicit delegation.
Show answerHide answer
Answer: D
The recorder holds the writer as a part, which is composition, and its method explicitly forwards the operation, which is delegation. No base-class relationship is needed. Automatic forwarding would use a mechanism such as __getattr__, while this interface lists the operation directly.

Question 7 of 10

A Notifier constructs NetworkSender() inside its initializer. Tests need to check message formatting without contacting the network. What change makes that straightforward?
  1. Make Notifier inherit from NetworkSender.
  2. Pass a sender into Notifier.__init__.
  3. Move the network call into a property getter.
  4. Copy the sender methods into Notifier.
Show answerHide answer
Answer: B
Constructor-supplied parts let a test pass a stand-in sender that records messages locally. The notifier can keep calling the same sender interface while the test controls the part. Inheriting from the network sender still ties the design to its behavior and does not by itself isolate network access.

Question 8 of 10

A task queue must allow only adding at the back and removing from the front. Its internal list may later be replaced. What design keeps callers independent of that storage choice?
  1. Subclass list and add a queue name.
  2. Expose the list and document its uses.
  3. Hold storage and expose queue methods.
  4. Return the list from a public property.
Show answerHide answer
Answer: C
A composed queue can offer only its intended add/remove operations and delegate them to private storage. Callers keep those methods if the underlying collection changes. A list subclass inherits many unrelated operations, while exposing or returning the list lets callers depend on its interface directly.

Question 9 of 10

What tuple results after this code?

class LowerDict(dict):
    def __setitem__(self, key, value):
        super().__setitem__(key.lower(), value)

d = LowerDict(A=1)
d["B"] = 2
d.update(C=3)
("b" in d, "c" in d, "A" in d)
  1. (True, True, False)
  2. (False, False, True)
  3. (True, True, True)
  4. (True, False, True)
Show answerHide answer
Answer: D
Construction stores "A" unchanged, direct assignment stores lowercase "b", and inherited update stores uppercase "C". Therefore "b" and "A" are present while lowercase "c" is absent. Treating all keys as normalized would assume that dict construction and update call the overridden assignment method.

Question 10 of 10

A plugin changes a base method to raise for an operation every caller of that base expects to work. What design problem does this expose?
  1. The subclass cannot fulfill the base’s public promise.
  2. The base needs more instance attributes on creation.
  3. The subclass must rename every inherited public method.
  4. The caller should compare exact types before all calls.
Show answerHide answer
Answer: A
The subclass breaks the behavioral promise that makes it usable through the base interface. The hierarchy should separate that capability or use suitable composed parts. Adding exact-type branches to every caller treats the symptom and makes each caller responsible for knowing which subclasses can actually work.
Set 2: Follow inheritance and method calls10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What tuple does the final expression return?

class Tool:
    label = "tool"

class Brush(Tool):
    label = "brush"

(Brush().label, Tool.label)
  1. ("tool", "tool")
  2. ("brush", "brush")
  3. ("brush", "tool")
  4. ("tool", "brush")
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What is the tuple at the end?

class Vehicle:
    wheels = 4

class Cart(Vehicle):
    pass

a, b = Cart(), Cart()
a.wheels = 3
(a.wheels, b.wheels, Vehicle.wheels)
  1. (3, 4, 4)
  2. (3, 3, 4)
  3. (3, 3, 3)
  4. (4, 4, 4)
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What exception does the final call raise?

class Job:
    def __init__(self, name):
        self.name = name

    def label(self):
        return self.name.upper()

class TimedJob(Job):
    def __init__(self, name, minutes):
        self.minutes = minutes

TimedJob("backup", 8).label()
  1. TypeError
  2. ValueError
  3. NotImplementedError
  4. AttributeError
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What tuple results?

class Meter:
    def __init__(self, start):
        self.value = start + 2

class OffsetMeter(Meter):
    def __init__(self, start, offset):
        super().__init__(start)
        self.value += offset

m = OffsetMeter(7, 4)
(m.value, isinstance(m, Meter))
  1. (11, True)
  2. (13, True)
  3. (13, False)
  4. (9, True)
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What list is returned?

class Root:
    def path(self):
        return ["R"]

class Left(Root):
    def path(self):
        return ["L"] + super().path()

class Right(Root):
    def path(self):
        return ["T"] + super().path()

class Combined(Left, Right):
    pass

Combined().path()
  1. ["L", "R", "T"]
  2. ["L", "R"]
  3. ["L", "T", "R"]
  4. ["T", "L", "R"]
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What string is returned?

class Base:
    def text(self):
        return self.tag()

    def tag(self):
        return "base"

class Wrap(Base):
    def text(self):
        return "[" + super().text() + "]"

class Mark(Base):
    def tag(self):
        return "mark"

class Page(Wrap, Mark):
    def text(self):
        return super().text() + "!"

Page().text()
  1. "[mark]!"
  2. "[base]!"
  3. "mark[!]"
  4. "[mark!]"
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What is type(value).__name__?

class Reading:
    def __init__(self, amount):
        self.amount = amount

    @classmethod
    def parse(cls, text):
        return cls(int(text))

class Peak(Reading):
    pass

value = Peak.parse("27")
  1. "Reading"
  2. "type"
  3. "int"
  4. "Peak"
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A replacement Timed.render must preserve every call valid for View.render. What definition does that while keeping prefix and suffix usable as keywords?

class View:
    def render(self, prefix="", *, suffix=""):
        return prefix + "view" + suffix
  1. def render(self, prefix, *, suffix=""):
  2. def render(self, prefix="", *, suffix="", stamp=False):
  3. def render(self, prefix="", *, suffix="", stamp):
  4. def render(self, prefix="", *, end="", stamp=False):
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A print_labels(items) function calls item.label() with no arguments and prints its returned string. What must an unrelated class provide to work in this function?
  1. A label attribute storing a string.
  2. A no-argument label() returning a string.
  3. A label(text) requiring a string argument.
  4. A shared base with a label class attribute.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

At what point does this code first raise an exception?

from abc import ABC, abstractmethod

class Source(ABC):
    @abstractmethod
    def read(self):
        ...

class FileSource(Source):
    pass

source = FileSource()
source.read()
  1. When Source is defined.
  2. When FileSource is defined.
  3. When FileSource() is called.
  4. When source.read() is called.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Predict built-in behavior for custom objects10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What does print([badge]) display?

class Badge:
    def __repr__(self):
        return "Badge(8)"

    def __str__(self):
        return "number eight"

badge = Badge()
  1. [number eight]
  2. [Badge(8)]
  3. ["number eight"]
  4. ["Badge(8)"]
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What happens at the final line?

class Label:
    def __init__(self, text):
        self.text = text

    def __eq__(self, other):
        if not isinstance(other, Label):
            return NotImplemented
        return self.text == other.text

labels = {Label("draft")}
  1. A one-element set is created.
  2. An AttributeError is raised.
  3. An empty set is created.
  4. A TypeError is raised.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What tuple results?

class LeftValue:
    def __eq__(self, other):
        return NotImplemented

class RightValue:
    def __eq__(self, other):
        return isinstance(other, LeftValue)

a, b = LeftValue(), RightValue()
(a == b, a is b, a != b)
  1. (True, False, False)
  2. (False, False, True)
  3. (True, True, False)
  4. (False, True, True)
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What change enables the final multiplication with the same numeric scaling meaning?

class Span:
    def __init__(self, meters):
        self.meters = meters

    def __mul__(self, factor):
        if not isinstance(factor, (int, float)):
            return NotImplemented
        return Span(self.meters * factor)

3 * Span(7)
  1. Add __radd__ = __mul__.
  2. Add __imul__ = __mul__.
  3. Add __rmul__ = __mul__.
  4. Add __mul__ = int.__mul__.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What tuple results?

class Bag:
    def __init__(self):
        self.items = []

    def __iadd__(self, item):
        self.items.append(item)

bag = Bag()
alias = bag
bag += "map"
(bag is None, alias.items)
  1. (False, [])
  2. (True, ["map"])
  3. (False, ["map"])
  4. (True, [])
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

The Distance class adds only another Distance; unsupported addition returns NotImplemented, and it has no __radd__. What expression totals a nonempty list named distances and returns a Distance?
  1. sum(distances, Distance(0))
  2. sum(distances)
  3. sum(distances, 0)
  4. sum(distances, None)
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What ordered list of codes results?

from dataclasses import dataclass, field

@dataclass(order=True)
class Ticket:
    urgency: int
    sequence: int
    code: str = field(compare=False)

tickets = [Ticket(2, 1, "a"), Ticket(1, 8, "b"),
           Ticket(1, 3, "z"), Ticket(2, 0, "c")]
[t.code for t in sorted(tickets)]
  1. ["a", "b", "c", "z"]
  2. ["z", "c", "a", "b"]
  3. ["b", "z", "a", "c"]
  4. ["z", "b", "c", "a"]
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What tuple results?

class Batch:
    def __len__(self):
        return 0

batch = Batch()
(bool(batch), batch is not None)
  1. (True, True)
  2. (False, False)
  3. (False, True)
  4. (True, False)
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What tuple results?

class Row:
    def __init__(self):
        self._values = [4, 7, 9]

    def __getitem__(self, index):
        return self._values[index]

r = Row()
(list(r), 7 in r, r[1:])
  1. ([4, 7, 9], True, [7, 9])
  2. ([4, 7, 9], False, [7, 9])
  3. ([4, 7, 9], True, [4, 7])
  4. ([4, 7], True, [7, 9])
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What happens at the final expression?

class Parcel:
    pass

p = Parcel()
p.__len__ = lambda: 6
len(p)
  1. It returns 6.
  2. It raises TypeError.
  3. It raises AttributeError.
  4. It returns 0.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Trace properties and dataclass setup10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What value is read at the end?

class Panel:
    def __init__(self, width, height):
        self.width, self.height = width, height

    @property
    def area(self):
        return self.width * self.height

p = Panel(6, 2)
p.width = 9
p.area
  1. 12
  2. 18
  3. 9
  4. 6
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What pair results?

from functools import cached_property

class Scores:
    def __init__(self):
        self.values = [2, 8]

    @cached_property
    def total(self):
        return sum(self.values)

s = Scores()
first = s.total
s.values.append(5)
(first, s.total)
  1. (10, 15)
  2. (15, 15)
  3. (15, 10)
  4. (10, 10)
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

After the exception is caught, what is r.value?

class Ratio:
    def __init__(self, value):
        self.value = value

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, new):
        if not 0 <= new <= 1:
            raise ValueError("out of range")
        self._value = new

r = Ratio(0.4)
try:
    r.value = 1.3
except ValueError:
    pass
  1. 0.4
  2. 1.3
  3. 1.0
  4. 0.0
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What tuple results?

class Base:
    def __init__(self):
        self.__score = 5

    def score(self):
        return self.__score

class Child(Base):
    def __init__(self):
        super().__init__()
        self.__score = 9

c = Child()
(c.score(), c._Child__score, len(c.__dict__))
  1. (9, 9, 1)
  2. (9, 9, 2)
  3. (5, 9, 2)
  4. (5, 5, 1)
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What field definition gives each folder its own default list?

from dataclasses import dataclass, field

@dataclass
class Folder:
    name: str
    # items field goes here
  1. items: list = []
  2. items: list = list
  3. items: list = field(default=list)
  4. items: list = field(default_factory=list)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What tuple results?

from dataclasses import dataclass, field

@dataclass
class Pack:
    masses: list[int] = field(default_factory=list)
    total: int = field(init=False)

    def __post_init__(self):
        self.total = sum(self.masses)

a = Pack([3, 8])
b = Pack()
a.masses.append(4)
(a.total, b.masses, sum(a.masses))
  1. (15, [], 15)
  2. (11, [], 15)
  3. (11, [4], 15)
  4. (15, [4], 15)
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What tuple results?

from dataclasses import dataclass, field

@dataclass
class Record:
    code: int
    note: str = field(compare=False, repr=False)
    limit = 10

a = Record(6, "first")
b = Record(6, "second")
(a == b, repr(a), "limit" in a.__dict__)
  1. (True, "Record(code=6)", False)
  2. (False, "Record(code=6)", False)
  3. (True, "Record(code=6)", True)
  4. (False, "Record(code=6, limit=10)", True)
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What is the length of points?

from dataclasses import dataclass

@dataclass(frozen=True)
class Pixel:
    x: int
    y: int

points = {Pixel(4, 6), Pixel(4, 6), Pixel(6, 4)}
len(points)
  1. 3
  2. 1
  3. 2
  4. A TypeError is raised.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What happens after the append and then the hash call?

from dataclasses import dataclass, field

@dataclass(frozen=True)
class Bundle:
    labels: list[str] = field(default_factory=list)

b = Bundle()
b.labels.append("fragile")
hash(b)
  1. The append raises FrozenInstanceError.
  2. The append succeeds; hashing returns an integer.
  3. The append succeeds; hashing raises FrozenInstanceError.
  4. The append succeeds; hashing raises TypeError.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What change permits Sensor("roof", serial=21) while keeping serial required?

from dataclasses import dataclass

@dataclass
class Device:
    site: str
    active: bool = True

@dataclass
class Sensor(Device):
    serial: int
  1. Give serial a default of 0.
  2. Use @dataclass(kw_only=True) on Sensor.
  3. Move serial to the top of Sensor’s body.
  4. Use @dataclass(frozen=True) on both classes.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Connect class design with runtime behavior10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What tuple results?

class End:
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.log = ["end"]

class Named(End):
    def __init__(self, *, name, **kwargs):
        super().__init__(**kwargs)
        self.name = name
        self.log.append("named")

class Ranked(End):
    def __init__(self, *, rank, **kwargs):
        super().__init__(**kwargs)
        self.rank = rank
        self.log.append("ranked")

class Entry(Named, Ranked):
    pass

e = Entry(name="Ira", rank=4)
(e.log, e.name, e.rank)
  1. (["end", "named", "ranked"], "Ira", 4)
  2. (["named", "ranked", "end"], "Ira", 4)
  3. (["end", "ranked", "named"], "Ira", 4)
  4. (["end", "named"], "Ira", 4)
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What tuple results?

class Sample:
    def __init__(self, value):
        self.value = value

    @classmethod
    def parse(cls, text):
        return cls(int(text))

    def score(self):
        return self.value + 1

class Weighted(Sample):
    def __init__(self, value):
        super().__init__(value * 2)

    def score(self):
        return super().score() * 3

s = Weighted.parse("5")
(type(s).__name__, s.score())
  1. ("Weighted", 33)
  2. ("Sample", 6)
  3. ("Weighted", 18)
  4. ("Sample", 33)
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What exception occurs at the final expression?

from abc import ABC, abstractmethod

class Reader(ABC):
    @abstractmethod
    def read(self):
        ...

class CountReader(Reader):
    def read(self, count):
        return "x" * count

r = CountReader()
r.read()
  1. NotImplementedError during read().
  2. TypeError during construction.
  3. AttributeError during read().
  4. TypeError during read().
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A key-normalizing map must normalize keys on direct assignment, construction, and update. A dict subclass overrides only __setitem__; direct assignment passes tests, but the other two routes leave mixed-case keys. What replacement addresses the cause while keeping dictionary-style operations?
  1. Keep the subclass and add a read-only key property.
  2. Use UserDict and keep normalization in __setitem__.
  3. Keep the subclass and normalize only in __getitem__.
  4. Use a list subclass and normalize items in append.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A value class compares only an immutable code field; a mutable note does not affect equality. What hash definition fits that equality rule?
  1. return hash(self.code)
  2. return hash((self.code, self.note))
  3. return id(self)
  4. return hash(self.note)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What tuple results?

class Amount:
    def __init__(self, n):
        self.n = n

    def __add__(self, other):
        if not isinstance(other, Amount):
            return NotImplemented
        return Amount(self.n + other.n)

values = [Amount(3), Amount(7)]
a = sum(values, Amount(0))
b = a
a += Amount(5)
(a.n, b.n, a is b)
  1. (15, 15, True)
  2. (10, 10, True)
  3. (15, 10, False)
  4. (15, 15, False)
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What value results?

class Offset:
    def __init__(self, shift):
        self.shift = shift

    def __call__(self, value):
        return value + self.shift

Offset(8)(6)
  1. 8
  2. 14
  3. 6
  4. 48
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What tuple results after the exception is caught?

class Capacity:
    def __init__(self, value):
        self.value = value

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        if value < 0:
            raise ValueError("negative capacity")
        self._value = value

class Reserved(Capacity):
    def __init__(self, value, reserve):
        super().__init__(value)
        self.reserve = reserve

    @property
    def available(self):
        return self.value - self.reserve

r = Reserved(20, 6)
try:
    r.value = -3
except ValueError:
    pass
r.reserve = 8
(r.value, r.available)
  1. (-3, -11)
  2. (20, 14)
  3. (-3, 12)
  4. (20, 12)
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What tuple results?

from dataclasses import dataclass, replace

@dataclass
class Reading:
    value: int
    scale: int = 2

    def __post_init__(self):
        self.value *= self.scale

a = Reading(3)
b = replace(a, scale=4)
(a.value, b.value)
  1. (6, 12)
  2. (12, 12)
  3. (6, 24)
  4. (3, 12)
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

On Python 3.12 or later, what tuple results?

from dataclasses import dataclass

class Logged:
    def __init__(self):
        self.ready = True

@dataclass(slots=True)
class Sensor(Logged):
    value: int

    def __post_init__(self):
        super(Sensor, self).__init__()

s = Sensor(9)
s.extra = "ok"
(s.ready, s.extra, hasattr(s, "__dict__"))
  1. (True, "ok", True)
  2. (True, "ok", False)
  3. (False, "ok", True)
  4. (False, "ok", False)
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

77 Key Terms, each with its definition

A

Abstract base class
An abstract base class defines required operations and can share working code while blocking incomplete subclass instances.
An exporter can require row formatting while providing the loop that joins formatted rows.
Abstract method
An abstract method is a method marked as required by an ABC; a subclass must make it concrete before normal instantiation.
Marking format_row with @abstractmethod makes a forgotten implementation fail at construction.
Aggregation
Aggregation describes a whole referring to parts that can exist independently and may also be shared with other objects.
A team can refer to player objects that existed before it and also belong to another team.
Alternative constructor
An alternative constructor creates an instance from another form of input, often through a named class method.
A from_csv class method can split a line and convert a salary before creating an employee.
Attribute shadowing
Attribute shadowing occurs when a more specific attribute is found before another attribute with the same name during lookup.
Assigning rex.legs = 3 gives that one dog object its own value while other dogs keep the value set on their class.

B

Base class
A base class supplies attributes and methods inherited by a subclass; it is also called a parent class or superclass.
An animal base can supply a name initializer shared by dog, cat, and bird subclasses.
Base initialization
Base initialization performs the setup a base class owns, including any state or validation needed by inherited methods.
Skipping account setup may leave a subclass without the balance that its methods try to read.
Bound method
A bound method is a method connected to an object so that the object is supplied automatically as its first argument.
Calling super().__init__(owner) supplies the instance already; passing self again adds an argument.

C

Cached property
A cached property computes a value on first access and stores it on the instance for later reads without recomputation.
A cached list total keeps its old result after an append unless the design refreshes that cache.
Callable object
A callable object supports function-call syntax; a class can make its instances callable by defining __call__.
A multiplier instance keeps its factor as state and applies it whenever the instance is called.
Class attribute
A class attribute belongs to the class and is available through its instances unless a more specific value shadows it.
Setting Animal.legs = 4 supplies a shared value that a bird subclass can specialize.
Class method
A class method receives the class used in the call as its automatic first argument, conventionally named cls.
An inherited parser can construct a subclass by returning cls called with parsed field values.
ClassVar
A ClassVar annotation marks a shared class variable that dataclasses exclude from generated field-based methods.
A record’s shared counter can remain a class variable instead of becoming a constructor parameter.
Compatible override
A compatible override preserves the calls and result meaning expected from the base method so clients can use the subclass.
Making a new parameter optional can keep a previously valid no-argument call working.
Composition
Composition builds an object from other objects held as attributes and models a relationship in which it has or uses parts.
An order holds line items and combines the subtotals that those items calculate themselves.
Concrete class
A concrete class has no remaining abstract methods and can be instantiated, provided its ordinary setup succeeds.
An exporter subclass becomes concrete after supplying the required row-formatting method.
Container protocol
The container protocol is the collection of special-method agreements behind operations such as indexing, length, and membership.
A deck can support length and indexed access by delegating those operations to a stored list.
Cooperative inheritance
Cooperative inheritance uses compatible methods that continue a shared MRO-based call chain, commonly through super().
Each initializer can consume its own keywords and forward remaining inputs to the next class.

D

Dataclass
A dataclass is a class decorated to generate routine methods from annotated fields while allowing ordinary custom behavior.
A point record can receive initialization, readable representation, and value equality from two field declarations.
Default factory
A default factory is a zero-argument callable used to create a field’s default value whenever an instance needs one.
Using list as the factory gives each notebook a fresh notes list instead of sharing one mutable default.
Delegation
Delegation forwards an operation from an outer object to a collaborating part, letting that part carry out the work.
A car’s public start method can forward the call to its stored engine’s start method.
Diamond inheritance
Diamond inheritance occurs when two inheritance paths from one class lead back to the same shared ancestor.
If both audit and stamp classes inherit an event base, combining them creates a diamond.
Duck typing
Duck typing accepts objects based on compatible operations they provide, without requiring them to share a base class.
An unrelated square class can join an area-summing loop if its no-argument method returns a number.

E

EAFP
EAFP is the style of attempting an operation and handling its expected failure instead of checking every condition first.
Catching a missing method lookup separately keeps errors inside the method from being hidden.

F

Field
A field is an annotated dataclass variable that participates in generated methods according to its field settings.
A mass field can be included in construction and display while a derived total omits the constructor parameter.
Fragile base class
The fragile base class problem arises when a subclass depends on internal base behavior that changes or differs from expectations.
A key-normalizing override can fail when an inherited update method bypasses that override.
Frozen dataclass
A frozen dataclass blocks ordinary field assignment and deletion, giving records fixed bindings while retaining any nested mutability.
A frozen pixel with hashable coordinates can use generated equality and hashing as a set member.

G

Getter
A getter is the method a property runs to obtain an attribute’s value, using stored state or a computation.
A radius getter reads _radius so it does not recursively access the public property again.

H

Hashability
Hashability means an object supplies a stable hash compatible with equality, allowing use as a dictionary key or set member.
A mutable dataclass with default equality is unhashable, so inserting it in a set raises TypeError.

I

Identity
An object’s identity distinguishes that particular object from every other object, regardless of their stored values.
Two separately constructed points can compare equal while is confirms that they are different objects.
In-place operator method
An in-place operator method handles augmented assignment and returns the result that is then assigned to the left-hand target.
A mutating __iadd__ normally returns self; omitting that return can rebind the name to None.
IndexError
IndexError signals an invalid sequence position and also ends the positional iteration fallback based on __getitem__.
A wrapper forwarding indexing to a list naturally raises this exception after its last valid position.
Initializer
An initializer is the __init__ method that sets up an already created instance using its supplied arguments.
A savings account initializer first runs account setup, then stores its interest rate.
Internal attribute
An internal attribute is storage intended for use inside a class, commonly marked by a single leading underscore.
Callers use a checked balance property or method instead of directly modifying _balance.
Invariant
An invariant is a rule the object’s valid state must continue to satisfy after construction and supported updates.
A nonnegative-length invariant needs the same validation during creation and later assignments.
isinstance
The isinstance function checks whether an object belongs to a given class or any subclass of it.
An electric car passes an instance check for both its own class and the general car class.
Iterator
An iterator supplies successive items and signals when traversal ends; a class’s __iter__ method must return one.
Returning iter(self._items) lets a custom collection reuse its stored list’s iterator.

K

KeyError
KeyError signals that a requested mapping key is absent and helps callers distinguish a missing key from an invalid position.
A grid backed by a dictionary raises this exception when a requested coordinate tuple has no stored cell.
Keyword forwarding
Keyword forwarding passes remaining named arguments to another method, commonly by unpacking a dictionary with **kwargs.
A color initializer consumes color and forwards width for the next initializer in the chain.
Keyword-only field
A keyword-only field must be supplied by name to a generated initializer and cannot be passed in its positional arguments.
A required subclass identifier can be keyword-only even after a defaulted base field.

L

Lexicographic ordering
Lexicographic ordering compares components in sequence and lets the first unequal participating component decide the result.
An ordered dataclass with major then minor fields compares the major release before its minor number.

M

Membership test
A membership test checks whether an item belongs to an object, using __contains__ or an available iteration fallback.
Without a custom membership method, a sequence can scan its items to test whether a card is present.
Method override
A method override is a subclass definition with an inherited method’s name that replaces or extends that implementation.
A manager’s pay method can call the employee calculation and then add a bonus.
Method resolution order
The method resolution order is the ordered sequence of classes Python uses to resolve inherited attributes for a class.
A simple diamond can have the order D, B, C, A, object, with the shared base searched once.
Mixin
A mixin is a small class that adds a reusable capability to another class and is usually not intended for independent use.
A JSON mixin can add serialization when its host provides storage with JSON-compatible values.
MutableMapping
A MutableMapping is an ABC that builds mapping helpers from item reading, writing, deletion, iteration, and length.
Once those five primitives work, a subclass can inherit operations such as get and update.

N

Name mangling
Name mangling transforms double-leading-underscore names using their defining class to reduce accidental subclass collisions.
A base and child using __id store distinct attributes named _Base__id and _Child__id.
NamedTuple
A NamedTuple is a named record type with tuple behavior, including positional indexing and unpacking, and fixed field bindings.
A small coordinate record can provide both point.x access and tuple unpacking into two names.
NotImplemented
NotImplemented is the special return value an operator method uses to decline an operand type and allow fallback dispatch.
Returning it from vector equality lets the other operand try its own comparison rule.
NotImplementedError
NotImplementedError is an exception raised when an operation lacks an implementation, often in a regular base method.
A subclass can be created successfully and later raise this exception through an unimplemented base method.

O

Ordering comparison
An ordering comparison determines relative position through methods such as __lt__, which implements the less-than operation.
A version class can compare numeric component tuples to sort release numbers correctly.

P

Polymorphism
Polymorphism lets the same operation work on objects of different classes, with each class providing its own behavior.
A loop calls area() on each shape while the shapes choose their own calculations.
Post-initialization hook
The post-initialization hook, __post_init__, runs after generated field assignment to validate data or perform derived setup.
A rectangle can reject nonpositive dimensions and then assign its derived area in this hook.
Property
A property is a managed attribute whose access runs a getter and may also provide methods for assignment or deletion.
A rectangle’s area property multiplies its current dimensions when the area attribute is read.
Public interface
A public interface is the set of supported operations and meanings a class offers to the code that uses it.
A stack wrapper can expose push and pop while keeping list sorting outside its intended interface.

R

Read-only property
A read-only property permits reading through its public name but has no setter, so ordinary assignment raises AttributeError.
A rectangle can expose a read-only area even while its width and height remain mutable.
Reflected operator method
A reflected operator method lets the right operand handle a binary operation when Python’s dispatch rules call for it.
A vector’s __rmul__ can support scalar multiplication written with the scalar on the left.
replace
The replace helper constructs a new dataclass instance from current field values with selected changes and leaves the original alone.
Replacing a frozen point’s x coordinate creates another point instead of assigning to the frozen field.
Representation
A representation is the precise developer-facing string returned by __repr__, ideally showing how a value is constructed.
A vector displayed inside a list uses its representation even if it also has a different user-facing string.

S

Sequence
A Sequence is a collection ABC whose subclasses implement length and indexing and inherit standard sequence helpers.
A playlist that supplies __len__ and __getitem__ can inherit count, index, and iteration.
Setter
A setter is the method a property runs on assignment, often to check a proposed value before updating internal storage.
A temperature setter rejects a value below absolute zero before changing the stored Celsius value.
Shallow immutability
Shallow immutability fixes an outer object’s references without necessarily preventing changes inside the objects those references hold.
Appending to a list in a frozen record changes that list without rebinding the frozen field.
Slice object
A slice object carries the start, stop, and step supplied by slicing syntax and can be passed through __getitem__.
Forwarding deck[:3] to the list a deck stores returns a list containing the first three cards.
Slots
Slots allocate declared instance attributes without a new instance dictionary; an inherited dictionary can still allow extra names.
A slotted dataclass based only on object rejects a misspelled extra field such as xx.
Special method
A special method has double underscores at both ends of its name and supplies behavior for built-in Python operations.
Defining __len__ on a class lets the built-in len use that class’s length behavior.
Static method
A static method is a function stored on a class that receives no automatic instance or class argument when called.
A class can group a small input-format helper with its other operations using @staticmethod.
Subclass
A subclass is a class that inherits from another class and can add or override behavior while preserving the base interface.
ElectricCar(Car) creates a specialization that should still work with code expecting a car.
Substitutability
Substitutability means a specialized object can fulfill the public expectations of callers written for its base type.
A subclass that disables a promised operation cannot safely replace the base for those callers.
Sum start value
A sum start value is the initial object combined with the first item by sum; Python uses integer zero by default.
Supplying a zero vector as the start avoids an unsupported first addition between zero and a vector.
super proxy
A super proxy continues attribute lookup after a particular class along the actual object’s method resolution order.
Inside one branch of a diamond, super() may find a method on the neighboring branch.

T

Test stand-in
A test stand-in is a simple replacement object that provides the interface needed to test a collaborating class.
A recording sender lets a message service test formatted output without contacting a network.
total_ordering
The total_ordering decorator generates missing ordering methods from equality and at least one supplied ordering comparison.
A class with __eq__ and __lt__ can gain <=, >, and >= through the decorator.
Truth value
An object’s truth value determines its treatment in a condition through __bool__, then length, or a default true result.
An empty deck can be falsy while still being an existing object distinct from None.
Type annotation
A type annotation records an intended value type and identifies dataclass fields without itself validating values at run time.
Annotating a point coordinate as float does not by itself reject a string passed to the constructor.

U

UserDict
UserDict is a standard-library dictionary wrapper whose methods support customization through overridable operations.
A key-normalizing subclass can route updates through its own assignment rule using this wrapper.

V

Value equality
Value equality compares objects using selected meaningful data, through behavior such as a class’s __eq__ method.
Two vectors can compare equal because their coordinate pairs match, despite separate identities.
Virtual subclass
A virtual subclass is recognized by an ABC through registration or a hook without inheriting that ABC’s implementations.
Registering a class as a sequence changes type recognition but does not add count or index.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started