Skip to content
BIASED

Classes and objects

Block 1 of 8~3 min

From a dict to a class

In the topic Files and exceptions, except LookupError caught a KeyError. That works because exception types are classes, and a KeyError is a special kind of LookupError. Ask Python for the chain:

>>> KeyError.__mro__
(<class 'KeyError'>, <class 'LookupError'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>)

int, str, list and the file objects from open are classes too. Every object is an instance of some class, and the class decides what the object holds and what it can do. This topic opens the Abstraction module: we write classes of our own.

Our running example is a training configuration. Read from JSON, it is a dict, and a dict forgives too much:

>>> import json
>>> cfg = json.loads('{"lr": 0.001, "epochs": 10}')
>>> cfg["epoch"] = 20
>>> cfg
{'lr': 0.001, 'epochs': 10, 'epoch': 20}

The typo "epoch" silently created a new key, and training still runs for 10 epochs. Nothing says which keys a config must have, and type(cfg) is just dict. A class gives the record a name and a fixed way of being made:

class Config:
    def __init__(self, lr, epochs=10):
        self.lr = lr
        self.epochs = epochs
>>> c = Config(0.001)
>>> c.lr, c.epochs
(0.001, 10)
>>> type(c), isinstance(c, Config)
(<class '__main__.Config'>, True)

Python follows three rules here.

  1. The class statement runs its body. Each def in it creates a name in a fresh namespace. At the end, Python builds a class object from that namespace and binds the name Config to it, the way def binds a function.
  2. Calling the class makes an instance. Config(0.001) creates an empty object of type Config, then calls __init__ with that object as the first argument and 0.001 as the next.
  3. __init__ initializes; it does not create. It gives the new object its attributes, self.lr and self.epochs, and returns None. The call Config(...) returns the object itself.

Answers are saved on the server and tied to this browser until you sign in.