liveBook · Manning

Class

As explained in Practices of the Python Pro

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

A class groups closely related data and behavior into a reusable template. Creating an instance turns its data into object state and its behaviors into methods. section 2.2.2 section 2.3

In Python, a class commonly provides:

  • Attributes that hold an instance’s state. section 2.2.2
  • Methods that receive self and can read or change that state. section 2.2.2
  • An __init__ initializer that establishes initial state when an instance is created. section 2.2.2

Refactoring a game into a class

A Rock, Paper, Scissors program begins with functions that repeatedly share choices and game data. A RockPaperScissorsSimulator class gathers those behaviors, stores human_choice and computer_choice, and lets simulate coordinate the interaction through self. An instance can then run the game with RPS.simulate().

How Practices of the Python Pro covers it

How deep it goes
Explains attributes, methods, self, and __init__, with inheritance appearing as a separate debugging and testing concern.
Examples
Demonstrates class extraction, initialization, self-based state access, and instance use through a Rock, Paper, Scissors simulator.
What it assumes
Assumes functions and data, then motivates classes through repeated relationships and separation of concerns.
What you can do after
Builds a Python class from cooperating functions and shared data, then creates an instance and invokes its behavior.
How it connects
Connects classes with functions, methods, modules, objects, separation of concerns, inheritance, and composition.

Also explained in

Compare how 21 books explain class →

Related concepts

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