Intermediate   Chapter 117 · 25 min read · Module 10: Object-Oriented Programming

Introduction to OOP

Learning objectives
  • After this chapter you can explain what a class and an object are.
  • You can define a simple class and create objects from it.
  • You can store data in attributes and use methods to act on it.
  • You can explain the idea of self in a method.
  • You can describe the four pillars of OOP at a basic level.

So far you have written programs with variables and functions. This works well for small tasks, but when a program grows, many separate variables and functions become hard to manage. Think about a game with players: each one has a name, a score and a position, and several functions must work with those values together.

Object-oriented programming, or OOP, solves this by bundling data and the functions that use it into one unit called an object. Python is an object-oriented language, and you have already used objects without knowing: every string, list and number is one.

This chapter introduces the main ideas in plain words and writes a first class. Later chapters will go deeper into constructors, inheritance and other features.

Objects you already know

In Python everything is an object. The text 'hello' is an object of type str. It holds data, the characters, and it has actions you can call, such as upper(). Data stored inside an object is called an attribute, and an action it can perform is called a method. A list has the method append, and a string has the method split.

Example 1: objects and methods
word = 'python'
print(type(word).__name__)
print(word.upper())
numbers = [3, 1, 2]
numbers.sort()
print(numbers)
str PYTHON [1, 2, 3]

Class and object

A class is a blueprint that describes what data and actions a kind of object will have. An object, also called an instance, is one real thing built from that blueprint. One class can produce many objects, each with its own data. The class Dog is the idea of a dog; a dog named Rex and a dog named Bella are two objects.

Class: a blueprint that defines the attributes and methods of a kind of object
Object (instance): a single thing created from a class, with its own attribute values

Your first class

You write a class with the class keyword, usually with a capitalised name. Inside you define methods with def. The special method __init__ runs automatically when an object is created and is used to set the starting attributes. The first parameter of every method is called self. It is the object itself, and through it you read and write that object's attributes.

Example 2: a Dog class
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def speak(self):
        return self.name + ' says woof'

rex = Dog('Rex', 3)
bella = Dog('Bella', 5)
print(rex.name, rex.age)
print(bella.speak())
Rex 3 Bella says woof

You create an object by calling the class like a function: Dog('Rex', 3). Python makes a new object and runs __init__ with it as self. The two objects rex and bella share the same methods but keep separate attribute values, so changing one does not change the other.

Methods that change data

A method can read and also change the attributes of its object. This is the real power of OOP: the data and the rules for changing it live together. For example, a bank account object can refuse a withdrawal when the balance is too low, and every part of the program is protected by the same rule.

Example 3: a method that updates state
class Counter:
    def __init__(self):
        self.value = 0

    def add(self, amount=1):
        self.value += amount

c = Counter()
c.add()
c.add(5)
print(c.value)
d = Counter()
print(d.value)
6 0

The four pillars of OOP

  • Encapsulation: keep data and the methods that use it together, and control access to it.
  • Abstraction: show a simple interface and hide the complicated details inside.
  • Inheritance: build a new class from an existing one and reuse its code.
  • Polymorphism: different classes can respond to the same method name in their own way.

You do not need all four today. Just remember that classes organise code around the things in your problem. Each pillar will get its own chapter.

Example 4: objects keep separate data
class Player:
    def __init__(self, name):
        self.name = name
        self.score = 0

    def win(self, points):
        self.score += points

a = Player('Asha')
b = Player('Ravi')
a.win(10)
b.win(4)
a.win(5)
print(a.name, a.score)
print(b.name, b.score)
Asha 15 Ravi 4

Why use OOP?

OOP makes large programs easier to understand because related data and behaviour sit in one place. It supports reuse, since a class can be used many times, and it models real things naturally: students, cars, invoices, buttons. It is not always needed. For a short script, plain functions are fine. Choose classes when you have several pieces of data that belong together and operations that work on them.

Example 5: functions versus a class
# separate variables and function
name = 'Rex'
age = 3
def describe(n, a):
    return n + ' is ' + str(a)
print(describe(name, age))

# the same idea as a class
class Pet:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def describe(self):
        return self.name + ' is ' + str(self.age)
print(Pet('Rex', 3).describe())
Rex is 3 Rex is 3
A common naming rule: class names use CapWords such as BankAccount, while variables and methods use lowercase_with_underscores.

Python syntax

Syntax
class ClassName:
    def __init__(self, parameter):
        self.attribute = parameter

    def method(self):
        return self.attribute
Syntax
obj = ClassName(argument)
obj.method()

Real-world applications

  • Games with players, enemies and items.
  • Banking and shop systems with accounts and products.
  • GUI programs where each button and window is an object.
  • Data models in web applications.

Common mistakes

Mistake: Forgetting self as the first parameter of a method.
Fix: Always write def method(self, ...).
Mistake: Writing name = name instead of self.name = name in __init__.
Fix: Use self. to store the value on the object.
Mistake: Calling a method without brackets, as in obj.speak.
Fix: Write obj.speak() to run it.
Mistake: Confusing the class with an object.
Fix: Remember the class is the blueprint and Dog('Rex') is one object built from it.

Important tips

  • Name classes with CapWords.
  • Keep one class focused on one idea.
  • Start with attributes and a couple of methods.

Key points summary

  • A class is a blueprint; an object is an instance.
  • Attributes hold data; methods are functions inside a class.
  • __init__ sets up a new object.
  • self refers to the current object.
  • The four pillars are encapsulation, abstraction, inheritance and polymorphism.

Exam and interview points

  • Define class, object, attribute and method.
  • __init__ is the initialiser, called when an object is created.
  • self is the first parameter of an instance method.
  • State the four pillars of OOP.

Quick revision

  • class Name: defines a blueprint.
  • Name(args) creates an object.
  • self.attr stores data on the object.
  • Methods are functions in a class.

Frequently asked questions

What is self?

It is the name for the object the method is working on. Python passes it automatically when you call obj.method().

Do I have to call it self?

It is only a convention, but everyone uses self, and you should too.

Can one class make many objects?

Yes. You can create as many objects as you like, and each has its own attribute values.

Is everything in Python an object?

Yes. Numbers, strings, lists, functions and even classes are objects.

Practise this chapter

19 practice questions Take the chapter quiz

Related chapters