- Learn
- Computer Science & IT
- Programming
- Intermediate Python
- Python Classes
Python Classes
Classes, Inheritance and Composition in Python
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
- 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 lookupDefine 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 withsuper(), so a subclass adds its own data without repeating or skipping the base class's setup. - Use multiple inheritance, the MRO and mixinsPredict the method resolution order of a class with several bases, write cooperative methods with
super(), and add a reusable capability with a mixin class.
- Create subclasses and trace attribute lookup
- 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 methodsReplace 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 typingCall 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 classesWrite abstract base classes with the
abcmodule, make subclasses implement the required methods, and use the ready-made abstract classes incollections.abc.
- Override and extend inherited methods
- 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 delegationGive a class other objects as attributes, delegate work to them, and keep the parts replaceable.
- Decide between inheritance and compositionApply 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.
- Build classes by composition and delegation
- Implement special methods so your objects print clearly, compare and hash correctly, work with operators, and behave like containers or functions.
- Represent and compare objectsWrite
__repr__and__str__for clear output, define equality with__eq__, and keep__hash__consistent with it. - Support comparison and arithmetic operatorsImplement ordering comparisons, arithmetic and reflected operators, and return
NotImplementedfor types your class does not handle. - Make objects work like containers and functionsImplement
__len__,__getitem__,__setitem__,__contains__,__iter__,__bool__and__call__so objects work withlen(), indexing,in, loops,iftests and call syntax.
- Represent and compare objects
- 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 @propertyTurn methods into attributes with
@property, keep computed values up to date, and make attributes read-only. - Validate data with setters and protect internal stateWrite 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.
- Create computed and read-only attributes with @property
- 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 validationDeclare fields with type annotations, give them safe defaults, and add validation and derived values in
__post_init__. - Configure frozen, ordered, keyword-only and inherited dataclassesUse 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.
- Define dataclasses with fields, defaults and validation
Python Classes study guide
1Build 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.
isinstanceandissubclassinclude 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 receivesself. 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
TypeErrorwhen the class is defined. - A mixin supplies one capability with clear expectations about the host object.
- Named base calls can repeat shared ancestor setup.
2Share 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 kind | First automatic argument | Typical purpose |
|---|---|---|
| Instance method | self, the object | Work with an object's state |
| Class method | cls, the class used in the call | Build an object from another input format |
| Static method | None | A 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
selfuse the actual object’s overrides, even inside base code. - Compatible overrides preserve accepted calls and expected results.
- A class method receives
cls; usingcls(...)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.
NotImplementedErroris raised; operator methods returnNotImplemented.
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
ABCand@abstractmethodprevent instantiation while required methods remain abstract.- An ABC can combine required operations with shared working methods.
- Stack
@abstractmethodclosest to the function. - A
Sequencesubclass 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.
3Build 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
| Question | Inheritance | Composition |
|---|---|---|
| What relationship does it express? | A specialized object is a base-type object | An object has or uses parts |
| What interface is exposed? | Inherited public methods plus additions | The outer class's chosen methods |
| How can behavior vary? | Through subclass definitions and overrides | Through the objects supplied as parts |
| What does reuse depend on? | The base interface and often its internal call structure | The 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.
UserDictandUserListsupport customization through their methods.- Depending on a base’s internal calls makes a subclass fragile.
4Make 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;istests identity.- Return
NotImplementedwhen 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_orderingfills comparisons from equality and one ordering method. - Reflected arithmetic supports the right operand when the left cannot handle the operation.
- Return
NotImplementedfor unsupported operand types. - Supply a matching start value when
sumcannot 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.
| Syntax | Special 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__; useIndexErrorto end positional iteration. - Truth tests use
__bool__, then__len__, then a default true value. - Use
is not Nonewhen 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.
5Compute 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.
6Use 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 option | Effect |
|---|---|
init=False | Omit the field from constructor arguments |
repr=False | Omit it from generated representation |
compare=False | Omit 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_factorysupplies a fresh mutable default when each instance needs one.fieldoptions 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.
| Options | Default hash behavior |
|---|---|
eq=True, frozen=False | Instances are unhashable |
eq=True, frozen=True | A field-based hash is generated |
eq=False | The 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
1Follow an object through its hierarchy
15 steps
- 1IntroductionFind 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.
- 2ExampleGive 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")Alertinherits__init__andlabel. Creatingastores its own name,"heat". The class attributekindis specialized without changingRecord.kind, so the base can still describe ordinary records. - 3ExplanationTrace the label read
a.label()finds nolabelon the instance or inAlert, then findsRecord.label. Inside it,selfis still the alert.self.kindfindsAlert.kind, andself.namefinds 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. - 4ChallengeChange 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 givesaits own shadowingkind;bstill reads the subclass value.isinstance(a, Record)remains true. Changing the instance value does not change its class or the inherited relationship. - 5ExampleAdd subclass setup
class TimedAlert(Alert): def __init__(self, name, minutes): super().__init__(name) self.minutes = minutesThis subclass takes an extra input. Its initializer replaces the inherited one, so it must arrange the setup that creates
name. Thesuper()call reaches the inherited initializer on the same object. After that call, subclass code can safely useself.nameand add its ownminutesattribute. - 6TipPass values, without a second self
A method obtained through
super()is already bound to the instance. Writesuper().__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. Cooperativesuper()calls can follow the hierarchy as it changes. - 7ChallengeExtend an ordinary method
Add this method to
TimedAlert. What doesTimedAlert("frost", 12).label()return?def label(self): return super().label() + f" ({self.minutes} min)"---reveal---
It returns
"alert: frost (12 min)". Setup storesnameandminutes; inherited lookup giveskindthe alert value.super().label()supplies the shared label first, and the override appends its own text.super()supports ordinary methods as well as initializers. - 8ExampleCreate 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): passBoth branches reach
End, forming a diamond. Each branch adds its label and continues.Endsupplies the final implementation that stops this method chain. - 9ExplanationFollow the actual object’s MRO
Event.__mro__isEvent, Audit, Stamp, End, object. ThereforeEvent().steps()returns['audit', 'stamp', 'end'].The surprising call is inside
Audit: on anEvent, itssuper()reachesStamp, not its direct baseEnd. On a plainAudit, the next class isEnd. The MRO preserves base-order requirements and lists each class once; it does not finish the first branch before considering the second. - 10ChallengeStop forwarding
In a new version of the previous diamond, replace only
Stamp.stepswith this method. What doesEvent().steps()return?def steps(self): return ["stamp"]---reveal---
It returns
['audit', 'stamp'].Auditstill forwards toStamp, but the new method never asks the next implementation to run.End.stepsis therefore skipped. A unique MRO does not itself execute every method; each cooperative method must continue the chain. - 11ExplanationConsume 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 = widthFor
class Label(Colored, Sized): pass,Label(color="blue", width=6)works. Each initializer consumes its named input and forwards the rest. Nothing remains whenobject.__init__runs; an unused keyword would raiseTypeErrorthere. - 12ConnectionAdd 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 callingjson.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.
- 13TipCheck 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
AbeforeBand another requiresBbeforeA, a combined class can have no valid MRO; defining it raisesTypeError. 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. - 14ChallengeCombine setup and lookup
Taggedinherits fromColoredandSizedabove, has no initializer, and definesdescribe(self)to returnf"{self.color}:{self.width}". A subclassWideTag(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. - 15RecapUse 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.
2Make one caller work across classes
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep the caller focused on its job
- 2ExampleLet base code call an override
- 3ExampleExtend the result
- 4ChallengePreserve an existing call
- 5ExplanationConstruct the class that received the call
- 6ChallengeFind a constructor that loses the subclass
- 7ExplanationUse operations across unrelated classes
- 8TipSeparate lookup failure from a method bug
- 9ChallengeCheck the actual operation
- 10ExampleMake the requirement explicit
- 11Key InsightShare code without weakening the requirement
- 12ChallengeSeparate completeness from compatibility
- 13ConnectionUse standard collection agreements
- 14ChallengeAdd a new output class
- 15RecapCheck calls, results, and requirements
3Design an object around its parts
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive each part a clear job
- 2ExampleStart with a small sender
- 3ExampleCompose the service
- 4ChallengeUse a recording part
- 5ConnectionDecide who owns the part
- 6ExplanationApply the is-a test to operations
- 7ExampleExpose a stack’s intended operations
- 8TipVerify every route through a built-in class
- 9ChallengeChoose reuse without extra operations
- 10ChallengeReplace delivery without changing callers
- 11RecapKeep the outside stable
4Give a custom type familiar Python behavior
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTranslate syntax into operations
- 2ExampleShow the values inside an object
- 3ExampleCompare coordinates
- 4Key InsightEquality changes hashing expectations
- 5ChallengeDistinguish equality from sameness
- 6ExplanationChoose a meaningful ordering
- 7ExampleCreate a new arithmetic value
- 8ExampleScale in either operand order
- 9TipInspect sum’s first operation
- 10ChallengeTrack an alias through +=
- 11ConnectionKeep operator meanings predictable
- 12ExampleWrap a sequence with two methods
- 13ExplanationLet the index object reach storage
- 14Key InsightIteration and membership have fallbacks
- 15ChallengeAn empty object is still present
- 16ExampleRetain settings in a callable instance
- 17ChallengeCombine collection and value behavior
- 18RecapRead each contract at the syntax boundary
5Keep attributes current and valid
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate public attributes from storage
- 2ExampleCompute a perimeter on access
- 3TipUse attribute syntax for a property
- 4ConnectionCaching changes update behavior
- 5ChallengeCompare a stored value and a live read
- 6ExampleValidate through one public name
- 7ChallengePreserve the old value on failure
- 8ExplanationUpdate linked attributes together
- 9ExampleRead mangled names in their defining class
- 10TipUse the simplest internal-name convention
- 11ChallengeConnect validation with a derived value
- 12RecapTrace every route that changes state
6Build and configure reliable dataclasses
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionRead a compact class as generated behavior
- 2ExampleGenerate methods from fields
- 3ExampleCreate a fresh list for each parcel
- 4ChallengeCheck default independence
- 5ExplanationChoose a field’s generated roles
- 6ExampleValidate after field assignment
- 7ConnectionCreate new records with helpers
- 8ExplanationFreeze field bindings, not everything inside
- 9ChallengeSeparate a generated hash from a usable hash
- 10ExamplePut the sorting priority first
- 11ExampleHandle inherited field defaults
- 12TipSelect keyword-only fields and slots carefully
- 13ExampleRun needed ordinary base setup
- 14ChallengeChoose a data structure for its interface
- 15ChallengeConnect replacement, order, and identity
- 16RecapInspect fields before trusting generated code
Python Classes practice questions
Set 1: Use shared interfaces and replaceable parts10 Practice Questions
Question 1 of 10
save(self) and later defines save(self, path) under the same name. What happens when an instance calls save() without a path?Show answerHide answer
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()
Show answerHide answer
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()])
Show answerHide answer
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()
Show answerHide answer
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"))
Show answerHide answer
["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
Recorder stores a writer and implements record(text) as self.writer.write(text). What relationship and action does this show?Show answerHide answer
__getattr__, while this interface lists the operation directly.Question 7 of 10
Notifier constructs NetworkSender() inside its initializer. Tests need to check message formatting without contacting the network. What change makes that straightforward?Show answerHide answer
Question 8 of 10
Show answerHide answer
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)
Show answerHide answer
"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
Show answerHide answer
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)
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)
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()
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))
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()
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()
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")
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
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
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?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()
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()
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")}
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)
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)
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)
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
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?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)]
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)
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:])
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)
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
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)
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
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__))
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
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))
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__)
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)
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)
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
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)
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())
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()
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
code field; a mutable note does not affect equality. What hash definition fits that equality rule?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)
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)
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)
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)
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__"))
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Abstract base class
Abstract method
format_row with @abstractmethod makes a forgotten implementation fail at construction.Aggregation
Alternative constructor
from_csv class method can split a line and convert a salary before creating an employee.Attribute shadowing
rex.legs = 3 gives that one dog object its own value while other dogs keep the value set on their class.B
Base class
Base initialization
Bound method
super().__init__(owner) supplies the instance already; passing self again adds an argument.C
Cached property
Callable object
__call__.Class attribute
Animal.legs = 4 supplies a shared value that a bird subclass can specialize.Class method
cls.cls called with parsed field values.ClassVar
ClassVar annotation marks a shared class variable that dataclasses exclude from generated field-based methods.Compatible override
Composition
Concrete class
Container protocol
Cooperative inheritance
super().D
Dataclass
Default factory
list as the factory gives each notebook a fresh notes list instead of sharing one mutable default.Delegation
start method can forward the call to its stored engine’s start method.Diamond inheritance
Duck typing
E
EAFP
F
Field
Fragile base class
Frozen dataclass
G
Getter
_radius so it does not recursively access the public property again.H
Hashability
TypeError.I
Identity
is confirms that they are different objects.In-place operator method
__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__.Initializer
__init__ method that sets up an already created instance using its supplied arguments.Internal attribute
_balance.Invariant
isinstance
isinstance function checks whether an object belongs to a given class or any subclass of it.Iterator
__iter__ method must return one.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.Keyword forwarding
**kwargs.color and forwards width for the next initializer in the chain.Keyword-only field
L
Lexicographic ordering
M
Membership test
__contains__ or an available iteration fallback.Method override
Method resolution order
D, B, C, A, object, with the shared base searched once.Mixin
MutableMapping
MutableMapping is an ABC that builds mapping helpers from item reading, writing, deletion, iteration, and length.get and update.N
Name mangling
__id store distinct attributes named _Base__id and _Child__id.NamedTuple
NamedTuple is a named record type with tuple behavior, including positional indexing and unpacking, and fixed field bindings.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.NotImplementedError
NotImplementedError is an exception raised when an operation lacks an implementation, often in a regular base method.O
Ordering comparison
__lt__, which implements the less-than operation.P
Polymorphism
area() on each shape while the shapes choose their own calculations.Post-initialization hook
__post_init__, runs after generated field assignment to validate data or perform derived setup.Property
Public interface
R
Read-only property
AttributeError.Reflected operator method
__rmul__ can support scalar multiplication written with the scalar on the left.replace
replace helper constructs a new dataclass instance from current field values with selected changes and leaves the original alone.Representation
__repr__, ideally showing how a value is constructed.S
Sequence
Sequence is a collection ABC whose subclasses implement length and indexing and inherit standard sequence helpers.__len__ and __getitem__ can inherit count, index, and iteration.Setter
Shallow immutability
Slice object
__getitem__.deck[:3] to the list a deck stores returns a list containing the first three cards.Slots
object rejects a misspelled extra field such as xx.Special method
__len__ on a class lets the built-in len use that class’s length behavior.Static method
@staticmethod.Subclass
ElectricCar(Car) creates a specialization that should still work with code expecting a car.Substitutability
Sum start value
sum; Python uses integer zero by default.super proxy
super proxy continues attribute lookup after a particular class along the actual object’s method resolution order.super() may find a method on the neighboring branch.T
Test stand-in
total_ordering
total_ordering decorator generates missing ordering methods from equality and at least one supplied ordering comparison.__eq__ and __lt__ can gain <=, >, and >= through the decorator.Truth value
__bool__, then length, or a default true result.None.Type annotation
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.V
Value equality
__eq__ method.Virtual subclass
count or index.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.