I1 · Python Programming for AI

Introduction to Classes and Objects

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.

12 min Intermediate · Sublevel Beginner Jump to the activity

What you need: The earlier topics of this module.

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.

Overview

  • A class is a blueprint that defines the data (attributes) and behaviour (methods) of a kind of object.
  • An object, or instance, is one thing built from a class: each student object has its own name and marks.
  • __init__ sets up a new object's attributes; self refers to the object being used.
  • Object-oriented programming rests on encapsulation, abstraction, inheritance and polymorphism.
  • Everything in Python is an object: numbers, strings, lists and functions all have methods.
  • scikit-learn models are objects: model = LinearRegression(); model.fit(X, y); model.predict(X_new).

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.

Key terms

Class
A blueprint describing the data and behaviour of a kind of object.
Object or instance
One particular thing created from a class.
Attribute
A piece of data stored on an object, such as student.name.
Method
A function defined inside a class that works on its objects.
__init__
The special method that sets up a new object's attributes.
self
The first parameter of a method, referring to the object the method is called on.

Types

A class is built from several kinds of member, and classes relate to each other through inheritance. These are the types to know.

1. Instance attributes

Data that belongs to one particular object.

  • How it works: They are usually set in __init__ as self.name = name, and each object keeps its own copy.
  • Example: asha = Student("Asha", [78, 85]) and ravi = Student("Ravi", [66, 72]) each store their own marks.
  • When to use it: Use them for anything that differs from object to object: names, balances, positions.

2. Class attributes

Data shared by all objects of a class.

  • How it works: They are written directly inside the class body, outside any method, and are read through the class or any object.
  • Example: class Student: school = "Kendriya Vidyalaya" gives every student the same school value.
  • When to use it: Use them for constants and counters shared by every instance; never for per-object data like lists of marks.

3. Instance methods

Functions defined in a class that work on one object, taking self as the first parameter.

  • How it works: Calling asha.average() passes asha as self automatically, so the method can read and change her attributes.
  • Example: def average(self): return sum(self.marks) / len(self.marks).
  • When to use it: Use them for behaviour that depends on an object's own data; most methods are of this kind.

4. Class methods and static methods

Methods marked @classmethod, which receive the class (cls), and @staticmethod, which receive neither the class nor an object.

  • How it works: Class methods often build objects in alternative ways; static methods are ordinary helper functions grouped inside the class.
  • Example: Student.from_csv_row("Asha,78,85") as a class method; Student.is_valid_mark(105) as a static method.
  • When to use it: Use class methods for alternative constructors and static methods for helpers that belong with the class.

5. Special (dunder) methods

Methods with double underscores, such as __init__, __str__, __len__ and __eq__, that Python calls automatically.

  • How it works: Defining __str__ controls what print(obj) shows; __len__ makes len(obj) work; __eq__ defines == between objects.
  • Example: def __str__(self): return f"{self.name}: {self.average():.1f}".
  • When to use it: Use them to make your objects behave like built-in types: printable, comparable and countable.

6. Inheritance

Creating a new class (child) that takes on the attributes and methods of an existing class (parent).

  • How it works: class Topper(Student): inherits everything; it can add new methods or override existing ones, and super() calls the parent's version.
  • Example: In scikit-learn, every classifier inherits common behaviour such as get_params() from a BaseEstimator class.
  • When to use it: Use it when the new class really is a kind of the old one; otherwise combine objects instead (composition).

Explained in detail

Bundling data with behaviour

So far, data and functions have lived separately: a dictionary for a student, and functions such as average(marks) that work on it. A class bundles them. A Student class can hold a name and marks as attributes, and offer methods such as average() and add_mark(). Each Student object carries its own data, and asking riya.average() automatically uses Riya's marks. This style, called object-oriented programming, became popular through languages such as Smalltalk in the 1970s and C++ in the 1980s, and it organises most large software today.

The pieces of a class

PieceExampleMeaning
class lineclass Student:Starts the blueprint; class names use CapWords
Constructordef __init__(self, name):Runs once when an object is created
Attributeself.name = nameStores data on this object
Methoddef average(self): ...Behaviour that can use the object's data through self
Creating an objectriya = Student("Riya")Calls __init__ with self as the new object
Calling a methodriya.average()Python passes riya as self automatically

You have been using objects all along

Everything in Python is an object. A string is an object of class str, which is why it has methods such as upper(); a list is an object of class list, with append() and sort(). When you write "hello".upper(), you are calling a method on an object, exactly as with riya.average(). type("hello") shows <class 'str'>. Writing your own classes simply lets you create new kinds of object that fit your problem.

Classes in AI libraries

Machine-learning libraries are built around classes. In scikit-learn, model = DecisionTreeClassifier(max_depth=3) creates an object; model.fit(X, y) is a method that trains it and stores what it learned as attributes; model.predict(new_X) is a method that uses those attributes. In PyTorch, you define a neural network by writing your own class that inherits from nn.Module. Inheritance, one class building on another, is beyond this introduction, but recognising the pattern of creating an object, configuring it and calling its methods will make the rest of the course feel familiar.

  • Forgetting self as the first parameter of a method gives a TypeError about arguments.
  • Attributes set in __init__ belong to each object; values written directly in the class body are shared by all objects.
  • Adding a __str__ method controls what print(riya) shows.

How it works

TermMeaningIn the Student example
ClassThe blueprintclass Student:
ObjectOne thing made from itmeera = Student("Meera", [91, 88])
AttributeData stored in an objectmeera.name
MethodA function belonging to the classmeera.average()
__init__Sets up each new objectStores name and marks
selfThe object the method is working onself.marks

In code

A Student class with two objects, each keeping its own data.

student_class.py
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

Question 1

1. What does __init__ do?

Question 2

2. In a method, self refers to…

Question 3

3. model = LinearRegression() in scikit-learn creates…

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