Classes: Bundling Data with the Code That Uses It
self to composition. The next project, a bank account, uses exactly these pieces.After this lesson, you will be able to:
- Write a class with __init__, instance attributes and methods, and create objects from it
- Explain what self is and rewrite obj.method(x) as Class.method(obj, x)
- Give a class a readable __repr__ and __str__
- Predict which attributes are shared between instances and which are per-instance, and avoid the shared mutable attribute bug
- Use @property for a computed or validated attribute, and build a class from smaller objects with composition
Before you start
#The Problem: A Dict and Functions That Drift Apart
Here is a small text dataset the way you would write it with what you know so far. The data is a dictionary, and each operation is a function that takes that dictionary.
dataset = {"name": "reviews", "rows": []}
def add_row(ds, text, label):
ds["rows"].append((text, label))
def positive_share(ds):
positives = sum(1 for _, label in ds["rows"] if label == 1)
return positives / len(ds["rows"])
add_row(dataset, "loved it", 1)
add_row(dataset, "waste of money", 0)
add_row(dataset, "works great", 1)
print(positive_share(dataset))Output:
0.6666666666666666
This is fine for one dictionary and two functions. Now add a model dictionary, a tokenizer dictionary and ten more functions, and watch what can go wrong.
dataset = {"name": "reviews", "rows": []}
model = {"name": "baseline", "majority": 1}
def add_row(ds, text, label):
ds["rows"].append((text, label))
# Mistake 1: nothing stops you from passing the wrong kind of dict
try:
add_row(model, "great", 1)
except KeyError as err:
print("KeyError:", err)
# Mistake 2: a typo on assignment does not fail, it quietly creates a new key
add_row(dataset, "loved it", 1)
dataset["rwos"] = [] # meant dataset["rows"] = [] to start over
add_row(dataset, "slow shipping", 0)
print("rows:", len(dataset["rows"]), "expected: 1")Output:
KeyError: 'rows'
rows: 2 expected: 1
rwos is a new key, the reset you meant to do never happened, and the dataset still holds its old row. The count is 2 where you expected 1, and every figure computed from those rows, such as positive_share, is now wrong with no error to point at it. Three weaknesses sit behind both.- Nothing ties
add_rowto datasets, so any dictionary can be passed to it. - The data has no fixed shape. A key exists only because some line created it.
- A reader cannot tell which functions belong to which dictionary.
#Your First Class: init and self
Here is the dataset as a class.
class Dataset:
def __init__(self, name):
self.name = name
self.rows = []
def add_row(self, text, label):
self.rows.append((text, label))
def positive_share(self):
if not self.rows:
return 0.0
positives = sum(1 for _, label in self.rows if label == 1)
return positives / len(self.rows)
reviews = Dataset("reviews")
reviews.add_row("loved it", 1)
reviews.add_row("waste of money", 0)
reviews.add_row("works great", 1)
print(reviews.positive_share())
print(reviews.name, len(reviews.rows))Output:
0.6666666666666666
reviews 3
The words, in the order they appear:
class Dataset:defines a new kind of object. Class names usePascalCase.Dataset("reviews")creates an instance (also called an object): one particular dataset. Python makes an empty object and then calls__init__on it, passing the arguments you wrote.__init__is the initializer. It runs once per new object and its job is to set up the starting data.self.name = namestores a value on this object. Values stored on an object are attributes:reviews.name,reviews.rows.add_rowandpositive_shareare methods: functions defined inside a class.
#What self is
self. You never pass it yourself: Python passes the object to the left of the dot.class Dataset:
def __init__(self, name):
self.name = name
self.rows = []
def add_row(self, text, label):
self.rows.append((text, label))
reviews = Dataset("reviews")
reviews.add_row("loved it", 1)
Dataset.add_row(reviews, "waste of money", 0)
print(len(reviews.rows))Output:
2
reviews.add_row("loved it", 1) and Dataset.add_row(reviews, "waste of money", 0) do the same thing. The first is the shorthand. Inside add_row, self is reviews, so self.rows is reviews.rows. Call the same method on a different dataset and self is that dataset instead. That is the whole mechanism, and it is the same as passing a dictionary into a function, with the dictionary moved in front of the dot.#A picture of an object
vars() shows the bundle.class Dataset:
def __init__(self, name):
self.name = name
self.rows = []
reviews = Dataset("reviews")
reviews.rows.append(("loved it", 1))
print(vars(reviews))
print(type(reviews))Output:
{'name': 'reviews', 'rows': [('loved it', 1)]}
<class '__main__.Dataset'>
reviews.add_row, Python looks in the object's own attributes first. add_row is not there, so it looks in the class, where it finds the function. The data lives on each object, and the methods live once on the class. The viz below runs the walk up from the object to the class for two methods and then for a name that exists nowhere, which is how an AttributeError happens.What does this print? train = Dataset("train") alias = train alias.add_row("fine", 1) copy = Dataset("train") print(len(train.rows), len(copy.rows))
#Methods That Change State: A Model with fit and predict
fit learns something and stores it, and predict uses it. This stub learns the most common label and predicts it every time.from collections import Counter
class MajorityModel:
def __init__(self):
self.majority = None
self.is_fitted = False
def fit(self, labels):
self.majority = Counter(labels).most_common(1)[0][0]
self.is_fitted = True
return self
def predict(self, rows):
if not self.is_fitted:
raise RuntimeError("call fit() before predict()")
return [self.majority for _ in rows]
model = MajorityModel()
try:
model.predict(["any text"])
except RuntimeError as err:
print("RuntimeError:", err)
model.fit([1, 0, 1, 0, 1])
print(model.majority, model.is_fitted)
print(model.predict(["new review", "another one", "third"]))
print(MajorityModel().is_fitted)Output:
RuntimeError: call fit() before predict()
1 True
[1, 1, 1]
False
fit and predict communicate only through self: fit writes self.majority and predict reads it, and no argument carries it between them. Second, each object has its own state, so a second MajorityModel() starts unfitted. Third, the class keeps its own promise: calling predict early raises a clear error instead of returning nonsense. A dictionary could never enforce that, because nothing owns the rule.fit ends with return self so you can chain model.fit(labels).predict(rows). That is the same convention scikit-learn uses, and it is optional.self.other_method(). Inside a class, anything you want to reach on the object needs self. in front of it, whether it is an attribute or a method.#Printing Objects: repr and str
Print an object that has no printing rules and you get this.
class Sample:
def __init__(self, text, label):
self.text = text
self.label = label
sample = Sample("loved it", 1)
print(sample)
print([sample])Output:
<__main__.Sample object at 0x7f3a1c2b9d50>
[<__main__.Sample object at 0x7f3a1c2b9d50>]
__init__.__repr__is for developers: an unambiguous description, ideally one that looks like the code that would build the object. The interpreter, debuggers, error messages and lists use it.__str__is for readers: a friendly summary.print()andstr()use it.
class Dataset:
def __init__(self, name):
self.name = name
self.rows = []
def add_row(self, text, label):
self.rows.append((text, label))
def positive_share(self):
if not self.rows:
return 0.0
positives = sum(1 for _, label in self.rows if label == 1)
return positives / len(self.rows)
def __repr__(self):
return f"Dataset(name={self.name!r}, rows={len(self.rows)})"
def __str__(self):
return f"{self.name}: {len(self.rows)} rows, {self.positive_share():.0%} positive"
reviews = Dataset("reviews")
for text, label in [("loved it", 1), ("waste of money", 0), ("works great", 1)]:
reviews.add_row(text, label)
print(reviews)
print(repr(reviews))
print([reviews])Output:
reviews: 3 rows, 67% positive
Dataset(name='reviews', rows=3)
[Dataset(name='reviews', rows=3)]
!r inside the f-string asks for the repr of the name, which adds the quotes. If you only write one of the two, write __repr__: when __str__ is missing, print() falls back to it.#Class Attributes vs Instance Attributes
self. inside __init__, so each object has its own. You can also write an assignment directly in the class body. That makes a class attribute, and there is exactly one of it, shared by every instance.class TokenCounter:
unknown = "<unk>"
def __init__(self):
self.counts = {}
def add(self, token):
self.counts[token] = self.counts.get(token, 0) + 1
a = TokenCounter()
b = TokenCounter()
a.add("the")
b.add("cat")
print(a.counts, b.counts)
print(a.unknown, b.unknown, TokenCounter.unknown)
a.unknown = "[UNK]"
print(a.unknown, b.unknown, TokenCounter.unknown)
print(sorted(vars(a)), sorted(vars(b)))Output:
{'the': 1} {'cat': 1}
<unk> <unk> <unk>
[UNK] <unk> <unk>
['counts', 'unknown'] ['counts']
a.unknown finds nothing on a and falls through to the class, so every counter sees <unk>. Writing a.unknown = ... never changes the class: it creates a new attribute on a alone, which then hides the class one for that object. That is why vars(a) now lists unknown and vars(b) does not. Class attributes suit constants and settings that every instance shares.#The shared mutable attribute trap
Now put the dictionary in the class body instead.
class TokenCounter:
counts = {}
def add(self, token):
self.counts[token] = self.counts.get(token, 0) + 1
a = TokenCounter()
b = TokenCounter()
a.add("the")
b.add("cat")
print(a.counts)
print(b.counts)
print(a.counts is b.counts)Output:
{'the': 1, 'cat': 1}
{'the': 1, 'cat': 1}
True
self.counts[token] = ... does not assign to self.counts; it changes the object that self.counts already points to. Nothing errors. Counts from the training set quietly leak into the validation set. This is the same evaluate-once rule as the mutable default argument in the functions lesson. The rule of thumb: constants and strings can be class attributes, and every list, dict or set that belongs to one object is created inside __init__.Each Run should keep its own list of losses. Right now every Run shares one list, so run 2 reports losses it never logged. Fix the class.
[0.9, 0.5] [0.7]
#@property: A Computed or Validated Attribute
@property decorator, which works like the decorators you wrote earlier in the track: it wraps the function underneath it and changes how it behaves.A computed property, with no stored value to fall out of date:
class LinearModel:
def __init__(self, weights, bias=0.0):
self.weights = weights
self.bias = bias
@property
def n_params(self):
return len(self.weights) + 1
model = LinearModel([0.5, -1.2, 3.0])
print(model.n_params)
model.weights.append(0.1)
print(model.n_params)
try:
model.n_params = 10
except AttributeError as err:
print(type(err).__name__)Output:
4
5
AttributeError
@name.setter. Python runs it on every assignment. The value is stored under a name with a leading underscore, _learning_rate. That underscore is a convention meaning "internal, use the property instead", and Python does not enforce it.class Trainer:
def __init__(self, learning_rate):
self.learning_rate = learning_rate
@property
def learning_rate(self):
return self._learning_rate
@learning_rate.setter
def learning_rate(self, value):
if value <= 0:
raise ValueError(f"learning_rate must be positive, got {value}")
self._learning_rate = value
trainer = Trainer(0.01)
trainer.learning_rate = 0.001
print(trainer.learning_rate)
try:
trainer.learning_rate = -1
except ValueError as err:
print("ValueError:", err)
try:
Trainer(0)
except ValueError as err:
print("ValueError:", err)Output:
0.001
ValueError: learning_rate must be positive, got -1
ValueError: learning_rate must be positive, got 0
self.learning_rate = learning_rate in __init__ also goes through the setter, so a bad value is rejected when the object is created, not just later. Callers still write trainer.learning_rate = 0.001, exactly as with a plain attribute. That is why you can start with a plain attribute and turn it into a property later without changing any calling code, and why you do not need getter and setter methods up front.#Composition: Objects That Have Other Objects
class Tokenizer:
def __init__(self, lowercase=True):
self.lowercase = lowercase
def tokenize(self, text):
if self.lowercase:
text = text.lower()
return text.split()
class TokenCounter:
def __init__(self):
self.counts = {}
def add(self, token):
self.counts[token] = self.counts.get(token, 0) + 1
def top(self, n):
ranked = sorted(self.counts.items(), key=lambda pair: pair[1], reverse=True)
return ranked[:n]
class Pipeline:
def __init__(self, tokenizer, counter):
self.tokenizer = tokenizer
self.counter = counter
def feed(self, text):
for token in self.tokenizer.tokenize(text):
self.counter.add(token)
counter = TokenCounter()
pipeline = Pipeline(Tokenizer(), counter)
pipeline.feed("The cat sat on the mat")
pipeline.feed("The dog sat on the log")
print(pipeline.counter.top(3))
print(pipeline.counter is counter)Output:
[('the', 4), ('sat', 2), ('on', 2)]
True
Pipeline does not copy the counter. It stores a reference to the same object, which is why pipeline.counter is counter is True: the memory model lesson's rule that assignment shares an object applies to attributes too. Each class does one job, you can swap the tokenizer without touching the counter, and a method on one object can call methods on another (self.counter.add(token)).class Dog(Animal):, called inheritance, which says "is a" and lets the new class reuse and override the parent's methods. It is powerful and also couples the two classes tightly, so reach for it when the "is a" really holds. The lesson titled "Advanced OOP, Part 1: Inheritance, MRO & ABCs" teaches it, including super(). There, OOP means object-oriented programming, and MRO means method resolution order, the order Python searches parent classes for a method. You will see it in class Net(nn.Module): from PyTorch, where __init__ and methods work exactly as here. If a class mostly holds fields, @dataclass writes __init__ and __repr__ for you, taught in the lesson titled "Advanced OOP, Part 2: Dataclasses, Enum & Protocols".#Common Mistakes
#Leaving self out of a method definition
class Dataset:
def __init__(self, name):
self.name = name
self.rows = []
def add_row(text, label):
self.rows.append((text, label))
reviews = Dataset("reviews")
try:
reviews.add_row("loved it", 1)
except TypeError as err:
print("TypeError:", err)Output:
TypeError: Dataset.add_row() takes 2 positional arguments but 3 were given
reviews as the first argument, so text received the object and the call had one argument too many. The message counts it for you: you wrote two arguments and Python sent three. Add self as the first parameter. (The message begins add_row() without Dataset. on Python versions before 3.10, and the site runs a newer one.)#Forgetting self. when storing or reading an attribute
class Dataset:
def __init__(self, name):
name = name
self.rows = []
def add_row(self, text, label):
rows.append((text, label))
reviews = Dataset("reviews")
try:
print(reviews.name)
except AttributeError as err:
print("AttributeError:", err)
try:
reviews.add_row("loved it", 1)
except NameError as err:
print("NameError:", err)Output:
AttributeError: 'Dataset' object has no attribute 'name'
NameError: name 'rows' is not defined
name = name only rebinds the local parameter, and rows alone is a variable that does not exist. On an object, always write self.name and self.rows.#A mutable default argument in init
class Dataset:
def __init__(self, name, rows=[]):
self.name = name
self.rows = rows
train = Dataset("train")
test = Dataset("test")
train.rows.append("x")
print(test.rows)Output:
['x']
def runs. The fix is the None pattern, with a fresh list built inside.class Dataset:
def __init__(self, name, rows=None):
self.name = name
self.rows = [] if rows is None else rows
train = Dataset("train")
test = Dataset("test")
train.rows.append("x")
print(test.rows)Output:
[]
#Expecting == to compare contents
class Sample:
def __init__(self, text, label):
self.text = text
self.label = label
print(Sample("hi", 1) == Sample("hi", 1))Output:
False
== on your own objects asks whether they are the same object, not whether their attributes match. Teaching == to compare contents is one of the data model lesson's topics.#Try It: A Running Mean
RunningMean that practises four pieces from this lesson: __init__ with a per-object list, a method that changes state, a computed @property and a __repr__. It is deliberately smaller than the next project. Checking inputs, True or False results, a history and one object working with another are left for the bank account, which comes next.RunningMean: a tracker with a computed property
Build RunningMean(name). It keeps `name` and `values` (a list, one per object, starting empty). `add(value)` appends a number to `values`. `mean` is a read-only property: the sum of the values divided by how many there are, or 0.0 when there are none. Give it a __repr__ like RunningMean(name='latency_ms', count=3, mean=100.0), where count is the number of values.
RunningMean(name='latency_ms', count=0, mean=0.0)
RunningMean(name='latency_ms', count=3, mean=100.0)
100.0
[] False
AttributeError__init__ with a list built per object, a method that updates self, a computed property and a __repr__. The bank account project uses each of those again and adds what this exercise left out: it rejects bad amounts with ValueError, returns True or False from withdraw, keeps a history of what happened, and has transfer move money between two account objects.#Recap
__init__ runs when you create an instance and sets up that data, and self is the object a method was called on, so obj.method(x) means Class.method(obj, x). Methods change state by writing to self, and later calls see the change.__repr__ should describe the object unambiguously for developers, and __str__ should read well for people. Class attributes are shared by every instance, which is right for constants and wrong for a list or dict, which belong in __init__. A property gives you a computed value that cannot go stale, or an assignment that validates its input. Objects can hold other objects as attributes, which is composition, and that is the default way to combine classes before you reach for inheritance.What does this print? class Run: losses = [] def log(self, x): self.losses.append(x) a, b = Run(), Run() a.log(0.9) b.log(0.4) print(a.losses)