Classes & Objects
A class is a blueprint for creating objects, and an object is one thing built from that blueprint. Classes let you bundle data and the actions that use it, so your code can model real things such as students, bank accounts or matatu routes.
Why object-oriented programming?
Imagine tracking students with separate variables: name1, form1, name2, form2 and so on. It quickly becomes a mess. Object-oriented programming (OOP) groups each student's data and behaviour into one neat package. Python is fully object-oriented: even numbers and strings are objects.
print(type(5))
print(type("Kuza"))
print("kuza".upper()) # strings have methods because they are objects
Defining a class and creating objects
Use the class keyword followed by a name in CapitalisedWords (called PascalCase). The simplest class has an empty body, written with pass.
class Phone:
pass
my_phone = Phone() # create (instantiate) an object
my_phone.brand = "Tecno" # attach data to it
my_phone.storage_gb = 128
print(my_phone.brand, my_phone.storage_gb)
print(type(my_phone))
Calling the class like a function, Phone(), creates a new object. __main__ in the type name just means the class was defined in the file you ran.
A proper class: data plus behaviour
Real classes set up their data in a special method called __init__ and define methods: functions that belong to the class.
class Student:
school = "Kuza High" # shared by every student
def __init__(self, name, form):
self.name = name # unique to each student
self.form = form
def introduce(self):
return f"I am {self.name} in Form {self.form} at {self.school}"
def promote(self):
self.form += 1
neema = Student("Neema", 3)
juma = Student("Juma", 4)
print(neema.introduce())
print(juma.introduce())
neema.promote()
print(neema.form, juma.form)
Here is what's happening:
Student("Neema", 3)creates a new object and automatically calls__init__withname="Neema"andform=3.selfis the object being worked on.self.name = namestores the value on that object.neema.introduce()calls the method; Python passesneemain asselffor you.- Calling
neema.promote()changed only Neema's form. Each object keeps its own data.
school attribute live on the class.The details of __init__ and self have their own page: The __init__ Method.
Key vocabulary
| Term | Meaning | In the example |
|---|---|---|
| Class | The blueprint or template | Student |
| Object / instance | One thing made from the class | neema, juma |
| Instantiation | Creating an object from a class | Student("Neema", 3) |
| Attribute | A piece of data stored on an object or class | name, form, school |
| Method | A function defined inside a class | introduce(), promote() |
Checking types and identity
print(isinstance(neema, Student)) print(isinstance(neema, str)) print(neema is juma) # two separate objects twin = neema # another name for the SAME object twin.name = "Neema W." print(neema.name)
Assigning an object to a new variable doesn't copy it. Both names point to the same object, so a change through one name shows up through the other, exactly like lists.
If you print an object without telling Python how, you get its class and memory address, which will differ on your computer:
print(juma)
You can make this friendlier with the __str__ method, covered in Dunder Methods.
Forgetting the brackets when creating an object: s = Student doesn't create a student; it just gives the class another name. Write s = Student("Amani", 2). Similarly, neema.introduce without brackets refers to the method instead of calling it.
When should you use a class?
Use a class when several pieces of data belong together and there are actions that work on that data, especially if you need many similar things. A bank account (owner, balance, deposit, withdraw), a quiz question (text, options, check answer) and a game character (health, position, move) are all good fits. For a small script that just transforms some numbers, plain functions are fine.
Key points
- A class is a blueprint; an object (instance) is one thing built from it.
- Create objects by calling the class:
Student("Neema", 3). - Attributes hold data; methods are functions that act on the object through
self. - Each object keeps its own data; assigning an object to another variable doesn't copy it.
Tip: use the ← and → keys to move between pages.
