Skip to main content

P01.9 · Objects and classes

A free, illustrated module of 4 lessons and one interactive in P01 Python from Zero: Classes and instances; Methods and state; Special methods: objects that act like built-ins; Inheritance and shared interfaces.

P01.9 L0 · Foundation 4 lessons · about 100 min Live · in review

Part of P01 Python from Zero in the Programming and Data track.

Every value in Python is an object with a type, and a class is how you make a type of your own. These four lessons draw a class and its instances in the memory diagram, build a Student record and a RunningMean that keeps its state between calls, give a Vector the special methods that print, ==, len and + call, and let two models of the study table inherit one mse from a parent Model, ending with scikit-learn’s models, which share the same fit and predict.

What you need first. Functions, frames and scope (P01.4), import and the dot that reaches into a module (P01.5.1), lists and dictionaries (P01.6), and try, except and first tests (P01.8).

Lessons

  1. Classes and instances P01.9.1 25 min

    Every value is an object with a type, and a class is how you make a type of your own. Write a Student class with __init__, see what self is, and draw each instance as a small table of its own attributes.

  2. Methods and state P01.9.2 25 min

    A method is a function stored in the class and called through an instance: a.add(55) means RunningMean.add(a, 55). Build a running mean that keeps its total and count between calls, and meet the list that every instance shares by mistake.

  3. Special methods: objects that act like built-ins P01.9.3 25 min

    print, ==, len and + call methods with fixed names on your objects. Give a two-number Vector __repr__, __eq__ and __add__ so that Vector(1, 2) + Vector(3, 4) == Vector(4, 6) is True, then let dataclass write such methods for a Student.

  4. Inheritance and shared interfaces P01.9.4 25 min

    A subclass gets its parent’s methods and may replace them. Build a parent Model whose mse calls self.predict, two children for the study table, MeanModel (mse 170.0) and LineModel (mse 8.0), and see that scikit-learn’s models share the same fit and predict.

The interactive

P01.9-X1 · Instance workbench. The class RunningMean drawn once with its methods, and buttons that make the instances a and b and call add with a chosen score on either; each instance’s own total and count update while the methods stay in the class. A switch moves the data to a list in the class body to show the bug in which every instance shares it. It lives in Methods and state.

Back to top