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.
- The
classstatement runs its body. Eachdefin it creates a name in a fresh namespace. At the end, Python builds a class object from that namespace and binds the nameConfigto it, the waydefbinds a function. - Calling the class makes an instance.
Config(0.001)creates an empty object of typeConfig, then calls__init__with that object as the first argument and0.001as the next. __init__initializes; it does not create. It gives the new object its attributes,self.lrandself.epochs, and returnsNone. The callConfig(...)returns the object itself.