Definition
How would you describe every student the same way, with their own name and marks?
A class is a blueprint that defines what data (attributes) and behaviour (methods) its objects will have. An object, or instance, is one thing made from that blueprint. The special method __init__ sets up each new object, and self refers to the particular object a method is working on.
In simple words
A class is a cookie cutter; objects are the cookies. The Student class says every student has a name and marks and can work out an average. Student("Meera", [91, 88]) makes one student. Each object keeps its own data, so changing Meera's marks doesn't touch Kabir's.
Why it matters
Every AI library is organised into classes. In scikit-learn, LinearRegression() creates a model object with fit() and predict() methods; in PyTorch, every network is a class. Understanding classes lets you read and use these libraries.
How it works
| Term | Meaning | In the Student example |
|---|---|---|
| Class | The blueprint | class Student: |
| Object | One thing made from it | meera = Student("Meera", [91, 88]) |
| Attribute | Data stored in an object | meera.name |
| Method | A function belonging to the class | meera.average() |
| __init__ | Sets up each new object | Stores name and marks |
| self | The object the method is working on | self.marks |
In code
A Student class with two objects, each keeping its own data.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def average(self):
return sum(self.marks) / len(self.marks)
def add_mark(self, mark):
self.marks.append(mark)
def report(self):
return f"{self.name}: average {self.average():.1f} from {len(self.marks)} tests"
meera = Student("Meera", [91, 88])
kabir = Student("Kabir", [64, 70, 75])
print(meera.report())
print(kabir.report())
meera.add_mark(79)
print("After a new test:", meera.report())
print("Kabir unchanged:", kabir.report())Output
Meera: average 89.5 from 2 tests Kabir: average 69.7 from 3 tests After a new test: Meera: average 86.0 from 3 tests Kabir unchanged: Kabir: average 69.7 from 3 tests
Try it yourself
Class vocabulary
Match each term to its meaning.
- Class
- Object
- Attribute
- Method
- __init__
Common mistakes
- Forgetting self as the first parameter of a method.
- Writing name = name instead of self.name = name in __init__, so nothing is stored.
- Calling a method without brackets: meera.average instead of meera.average().
Check yourself
Summary
- A class is a blueprint; objects are made from it.
- Attributes store data; methods are the class's functions.
- __init__ sets up objects and self is the current object.
Finished reading?
Sources: Python docs: Classes