class Counter__init__(self, start)add(self, n)add(n)1class Counter:2 def __init__(self, start):3 self.count = start4 def add(self, n):5 self.count += n6c = Counter(5)7c.add(2)8d = Counter(0)9print(c.count, d.count) def add(n):Counter objectcCounter objectdTypeErrorCounter(5)count = 5addCounter(0)7 0
Code card: counter.py; the highlighted line is the one runningClass object Counter: the blueprint, holding the methodsInstance boxes: one Counter object each, with its own countTerminal: where print() writes and errors appearA class is a blueprint: running class Counter: builds one class object that holds the methods __init__ and add. Each step lights the parts it is about. Calling Counter(5) makes a new, empty object and __init__ fills in its count; the name add hops back to the class, where Python finds the method; count changes from 5 to 7; Counter(0) makes a second object with its own count; print() shows 7 0. In the last step self is removed from line 4, and line 7 stops with a TypeError: Python passed two arguments to a method that takes one.

The class

  1. class Counter: starts a class, a blueprint for making objects. Python runs the indented body once and builds a class object named Counter that holds everything defined inside it. No Counter object exists yet.

Make an object

Methods at work

One rule

Try it yourself

;; step 1/9 · line 1: class Counter:
>>> class Counter:
...     def __init__(self, start):
...         self.count = start
...     def add(self, n):
...         self.count += n
...
>>> Counter
<class '__main__.Counter'>

self is only a convention: Python passes the object as the first argument whatever that parameter is called. Every Python programmer still calls it self. The figure shortens the traceback: it leaves out the lines that name the file and show line 7, and wraps the long last line onto two rows. Python 3.10 and later name the method as Counter.add().