Object-Oriented Programming
Classes, objects, attributes and methods, and inheritance as it appears in AI libraries.
Class and object
class Dataset:
def __init__(self, name, samples):
self.name = name # an attribute
self.samples = samples
def size(self): # a method
return len(self.samples)
ds = Dataset("iris", [1, 2, 3])
print(ds.name, ds.size()) # iris 3self refers to the current object, and it is passed automatically on the call.
Inheritance
class ImageDataset(Dataset):
def __init__(self, name, samples, size_px):
super().__init__(name, samples)
self.size_px = size_px
def describe(self):
return f"{self.name}: {self.size()} images of size {self.size_px}"super() calls the methods of the parent class.
Special methods
Methods that start and end with two underscores let the class integrate with the language:
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
Vector(1, 2) + Vector(3, 4) # Vector(4, 6)__len__ and__getitem__ make the object support len() and indexing, which is what the class Dataset requires in PyTorch.
Object-oriented programming in AI
import torch.nn as nn
class TinyNet(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Linear(4, 3)
def forward(self, x):
return self.fc(x)The layers are defined in __init__ and the computation is defined in forward. A good understanding of classes and inheritance makes reading this code natural.
Lesson terms
- Class
- A template that describes the data and behaviour of a group of objects.
- Object
- A specific instance created from a class, with its own attribute values.
- Inheritance
- A mechanism that lets a subclass take the attributes and methods of a parent class, with the ability to extend or modify them.
Abstract
Object-oriented programming organizes code around classes that combine data (attributes) and behaviour (methods). An object is created from the class and initialized by the __init__ method, and inheritance makes it possible to build a new class that extends an existing one. This pattern is essential in libraries such as PyTorch, where a model inherits from nn.Module.
Review questions
-
What is the role of self in class methods?
It refers to the current object on which the method was called, and through it we reach its attributes.
-
What is the benefit of inheritance?
Reusing and extending the behaviour of an existing class without repeating code.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate