liveBook · Manning

Class

As explained in Python How-To

A class is a programming-language construct that defines a type’s structure or behavior and provides a basis for creating or representing objects.

Need to represent tasks with their own data and operations? Define a class. A class is a Python type: calling it creates an instance, and its attributes and methods give that instance a useful shape. Built-in types such as list and dict are classes too. A custom class lets an application model needs that generic containers do not express well. section 5.1 section 8.0

Initialize a task

class Task: def __init__(self, title, desc, urgency): self.title = title self.desc = desc self.urgency = urgency task = Task("Laundry", "Wash clothes", 3) print(task.__dict__) # {'title': 'Laundry', 'desc': 'Wash clothes', 'urgency': 3} Calling Task creates an instance; __init__ sets its essential attributes from the supplied arguments. Put __init__ first and initialize every instance attribute there, even when an initial value must be None. That makes the available data easier to discover. section 8.1.2 section 8.1.5

Choose the shape that fits the job:

  • For a lightweight data holder, compare a custom class with a named tuple. Lists and tuples obscure field meanings; dictionary keys name fields but can be mistyped. A class becomes especially useful when data needs related methods. section 3.3.1 section 8.0
  • Use instance methods for instance behavior, class attributes for values shared by all instances, and static or class methods where those method forms fit. Properties can control changes to data; __str__ and __repr__ provide useful string representations. section 8.6
  • Use @dataclass to avoid routine __init__ and __repr__ boilerplate. For a set of enumerated values, subclass Enum rather than treating integer-valued class attributes as enumeration members. section 9.1.1 section 9.6

Use a class as a type hint

class User: pass def assign_task(pending_task: Task, user: User): pass A defined custom class can name an expected parameter type just as a built-in type can. Here pass is only a placeholder: real methods need implementations. section 6.3.3

Keep each class focused on one purpose. If a large class mixes, for example, account and demographic responsibilities, group its attributes and methods by function, then consider splitting it into distinct classes. A UML diagram can make that structure visible. Test a class chiefly through its methods, and revisit its design as the project grows; related classes should work together without becoming tightly coupled. section 9.5.1 section 9.5.4 section 13.4

How Python How-To covers it

How deep it goes
Works through initialization, method kinds, encapsulation, string representations, inheritance, and refactoring, then places instances in an object-lifecycle discussion.
Examples
Uses task initialization and type hints, an unsuccessful integer-valued enumeration, and a mixed-purpose student data model.
What it assumes
Assumes familiarity with built-in containers and functions while teaching custom initialization and class design through examples.
What you can do after
Build it from scratch: define and initialize focused custom classes, select suitable method forms, and refactor classes whose responsibilities have grown mixed.
How it connects
Connects classes to instances, named tuples, type hints, dataclasses, enumerations, UML diagrams, and automated testing.

Also explained in

Compare how 21 books explain class →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.