MEPX
Chapter 13 of 15All chapters

Chapter 13 of 15

Classes and objects

Bundling data with the code that works on it.

Defining a class

class defines a type, and __init__ runs when you create an instance. Every method takes self first, which is the instance the method was called on.

  • Attributes set in __init__ belong to the instance; ones set in the class body are shared.
  • __str__ decides what print shows, which is worth writing early.

Inheritance

A class can extend another by naming it in the parentheses, and super() calls the parent version of a method. Python allows several parents, but a single clear line of inheritance is easier to follow.