1. Home
  2. Explore
  3. Computer Science
  4. Object-Oriented Programming in Python

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Object-Oriented Programming in Python

Object-Oriented Programming in Python

Programming paradigms

A programming paradigm is a general approach to organizing and solving problems with code. Different languages support different paradigms, and a single language can support several.

  • Procedural programming organizes a program as procedures or functions. The program typically proceeds step by step, often from top to bottom.

  • Functional programming treats functions as values that can be passed to and returned from other functions. Anonymous functions are one feature associated with this style.

  • Object-oriented programming (OOP) organizes related data and functionality into objects created from classes.

Python supports all three approaches. Procedural code is often sufficient for small programs, but as a program becomes longer or more complex, OOP can help group related information and behavior, improve organization, and control how data is used.


Organizing data before using classes

Consider a program that asks for a student's name and school house, then prints a sentence such as “Harry from Gryffindor.”

Begin with procedural code

The simplest version collects and prints the values directly:

name = input("Name: ")
house = input("House: ")
print(f"{name} from {house}")

This works, but the operations are all written together. Functions can separate parts of the task and give them meaningful names.

Use functions to create abstractions

A function can hide the details of how a value is collected:

def get_name():
    return input("Name: ")

def get_house():
    return input("House: ")

The main procedure can then call those functions without needing to know how each one works:

def main():
    name = get_name()
    house = get_house()
    print(f"{name} from {house}")

if __name__ == "__main__":
    main()

This is an abstraction: a function provides a useful operation while hiding its implementation details. The if __name__ == "__main__": guard ensures that main() runs when the file is executed directly, but not automatically when the file is imported as a module.

If the program needs a complete student rather than separate values, a get_student() function can collect both:

def get_student():
    name = input("Name: ")
    house = input("House: ")
    return name, house

Python allows a function to appear to return multiple values this way. More precisely, the comma creates and returns one tuple containing both values.


Tuples, lists, and dictionaries

Python provides general-purpose containers for grouping values. Their differences matter when choosing how to represent related information.

Tuples

A tuple is an ordered, immutable collection of values. A comma creates a tuple, and parentheses can make the tuple explicit:

def get_student():
    name = input("Name: ")
    house = input("House: ")
    return (name, house)

The tuple can be unpacked into separate variables:

name, house = get_student()

Alternatively, the tuple can be stored as one value and accessed by numerical index:

student = get_student()
print(f"{student[0]} from {student[1]}")

Python uses zero-based indexing, so student[0] is the first element and student[1] is the second.

Immutability means that the tuple’s elements cannot be reassigned after the tuple is created. For example, an assignment such as student[1] = "Ravenclaw" raises a TypeError. Tuples are useful when a group of values should remain fixed, since they prevent accidental changes to the tuple’s contents.

A tuple can contain different kinds of values, including lists or other tuples. The tuple’s own element references cannot be reassigned, although a mutable object stored inside it may itself be changed.

Lists

A list is an ordered, mutable collection. Square brackets create a list:

student = [name, house]
student[1] = "Ravenclaw"

Lists also use square brackets for indexing, but their contents can be changed after creation. A list can contain values of different types, including other lists.

A list is appropriate when its elements may need to be added, removed, or updated. Its mutability also means that code can change it unintentionally, so it is not ideal when the values should remain fixed.

Dictionaries

A dictionary stores key–value pairs. Keys give descriptive names to values, so code does not need to rely on remembering an element’s numeric position:

student = {
    "name": name,
    "house": house,
}

Values are retrieved or changed using keys:

print(f"{student['name']} from {student['house']}")
student["house"] = "Ravenclaw"

Dictionaries are mutable. They are often clearer than tuples or lists when values have distinct meanings, especially when there are several fields. A dictionary makes the association between a label and its value explicit: "name" identifies the student's name, and "house" identifies the house.

The delimiters have different roles:

  • Creating a list: square brackets, such as [1, 2]

  • Creating a tuple: parentheses or a comma, such as (1, 2) or 1, 2

  • Creating a dictionary: curly braces with key–value pairs, such as {"name": "Harry"}

  • Accessing an element: square brackets for lists, tuples, and dictionaries; the contents inside the brackets differ depending on the type.

Type

Ordered

Mutable

Access method

Tuple

Yes

No

Numeric index

List

Yes

Yes

Numeric index

Dictionary

Insertion-ordered in modern Python

Yes

Key


Classes and objects

Tuples, lists, and dictionaries can represent a student, but they do not define a dedicated “student” type. A class lets a programmer define a custom data type with a meaningful name and a structure suited to the problem.

A class is a blueprint or template for creating objects. An object is a particular instance of a class.

For example, a Student class can describe what information belongs to a student. A particular student object can then store a specific name and house.

class Student:
    ...

The ellipsis is a valid placeholder when a class body has not yet been implemented. By convention, programmer-defined class names use CapWords capitalization, as in Student. Many built-in Python types, such as int, str, list, and dict, use lowercase names.

An object is created by calling the class:

student = Student()

This is called instantiating the class. The resulting object is an instance of Student. A class can be used to create many objects, each with its own data.

Attributes and instance variables

An object can store data in attributes, which are accessed with dot notation. An instance variable is an attribute associated with a particular object.

student.name = "Harry"
student.house = "Gryffindor"

These attributes belong to the student object. Another Student object can have different values.

Initializing objects with __init__

Manually adding attributes after creating an object makes it easy to create objects inconsistently. A class can standardize the data each object receives by defining the special method __init__:

class Student:
    def __init__(self, name, house):
        self.name = name
        self.house = house

An object is then created with the values that will initialize it:

student = Student("Harry", "Gryffindor")

The class call appears to receive two arguments, but Python automatically supplies the object itself as the first argument to __init__. By convention, this first parameter is named self.

  • self refers to the object currently being initialized or used.

  • self.name = name creates or updates an instance variable called name on that object, assigning it the value supplied through the name parameter.

  • self.house = house does the same for the house instance variable.

The parameter and the instance variable may have the same name, but they are different things: the parameter is a value passed into the method, while self.name is data stored in the object.

The call Student("Harry", "Gryffindor") is often called a constructor call because it produces a new object. Python’s __new__ mechanism creates the object; __init__ then initializes the object’s contents. In typical Python programs, a programmer defines __init__ and lets Python handle object creation.

Methods and instance methods

A method is a function defined inside a class. An instance method operates on a particular object and receives that object as its first argument, conventionally named self.

A class can also define special methods that Python calls automatically for particular operations. Their names begin and end with double underscores; they are sometimes informally called dunder methods.


Validating data and raising exceptions

A class can help ensure that its objects contain valid data. For example, a student should have a non-empty name and one of the permitted Hogwarts houses.

Validation can be included in __init__:

class Student:
    def __init__(self, name, house):
        if not name:
            raise ValueError("Missing name")

        if house not in ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]:
            raise ValueError("Invalid house")

        self.name = name
        self.house = house

In Python, if not name is a concise way to check whether name is empty or otherwise false-like. A user who presses Enter without entering a name causes a ValueError to be raised.

raise signals that an exceptional condition has occurred. Exceptions can be caught with try and except, allowing the calling code to handle the problem without necessarily terminating the entire program. For example, code that creates a student could catch ValueError and ask the user to try again.

Printing an error message is not equivalent to raising an exception: printing reports something but does not stop the invalid operation from continuing. Exiting the entire program may also be too drastic. Raising a relevant exception allows the calling code to decide how to respond.

Validation in a class keeps checks close to the data they protect. This is an example of encapsulation: related data and behavior are kept together.


String representations with __str__

Printing an object without customizing its representation typically produces a technical description that includes its class and an address-like value. That output is useful to Python internally but is usually not informative to a user.

A class can define __str__ to specify a readable string representation:

class Student:
    def __init__(self, name, house):
        self.name = name
        self.house = house

    def __str__(self):
        return f"{self.name} from {self.house}"

When print(student) needs a string for the object, Python calls student.__str__() automatically. The method receives self, so it can use the object’s attributes.

Python also has __repr__, which provides a representation generally intended to be useful to developers. In broad terms, __str__ is typically the more user-friendly representation, while __repr__ may include more technical detail.


Properties: controlled attribute access

Even when a class validates its data in __init__, a programmer can later change public attributes directly:

student.house = "Number Four, Privet Drive"

This bypasses validation performed only during initialization. Properties provide a way to control attribute access using familiar dot notation.

A property commonly has:

  • A getter, which retrieves the value.

  • A setter, which validates and updates the value.

class Student:
    def __init__(self, name, house):
        self.name = name
        self.house = house

    def __str__(self):
        return f"{self.name} from {self.house}"

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, name):
        if not name:
            raise ValueError("Missing name")
        self._name = name

    @property
    def house(self):
        return self._house

    @house.setter
    def house(self, house):
        if house not in ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]:
            raise ValueError("Invalid house")
        self._house = house

The @property decorator makes the getter accessible as an attribute. The setter decorator, such as @house.setter, associates a setter with that property.

With these methods, the statements below use the property automatically:

student = Student("Harry", "Gryffindor")
print(student.house)
student.house = "Ravenclaw"

Reading student.house calls the getter. Assigning to student.house calls the setter, which can reject invalid values. Since __init__ assigns to self.name and self.house, those assignments also go through the setters. Validation can therefore be kept in one place instead of being duplicated in __init__ and elsewhere.

The getter and setter use an underlying instance variable with a different name, often prefixed with an underscore. For example, the property house uses _house to store the value. This avoids a naming collision between the property and the stored instance variable.

Python’s underscore convention

A leading underscore is a convention, not a strict access restriction. It signals that an attribute is intended for internal use and should generally not be accessed directly by other code. Python does not make the attribute truly inaccessible: code can still access student._house, bypassing the property and its validation.

A double leading underscore can make such access more difficult through name mangling, but it is not an absolute security boundary either. Python relies heavily on conventions and programmer cooperation rather than enforcing visibility rules as strictly as some languages do.


Class variables and class methods

Not every value or operation belongs to one particular object. Some information or behavior applies to the class as a whole.

Class variables

An instance variable belongs to an individual object and is usually accessed through self. A class variable belongs to the class and is shared by its instances.

A sorting hat might use one common list of houses:

class Hat:
    houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]

Because this list is defined in the class body rather than inside an instance’s __init__, it is a class variable. It can be accessed through the class, as in Hat.houses.

Class methods

A class method operates on the class rather than on one particular instance. The @classmethod decorator marks a method as a class method. By convention, its first parameter is named cls, a reference to the class itself.

import random

class Hat:
    houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]

    @classmethod
    def sort(cls, name):
        house = random.choice(cls.houses)
        print(f"{name} is in {house}")

It can be called directly on the class:

Hat.sort("Harry")

The method uses cls.houses rather than self.houses because it does not need a particular hat object. A class method can be useful when functionality belongs to the class as a whole or when it needs to create an instance of the class.

A class method does not necessarily imply that the class can have only one object. If a program needs exactly one shared object, that design is called a singleton; using a class method alone does not enforce singleton behavior.


Organizing class-related functionality

When functions and data relate to a particular kind of object, placing them in the class can make a program easier to understand. For instance, if collecting a student’s information is student-related behavior, it may be clearer to place that operation in the Student class rather than in a separate, unrelated function.

A class method can serve as a factory method: a class-level operation that gathers information and returns a new instance.

class Student:
    def __init__(self, name, house):
        self.name = name
        self.house = house

    @classmethod
    def get(cls):
        name = input("Name: ")
        house = input("House: ")
        return cls(name, house)

A program can then write:

student = Student.get()

The class method receives cls without needing an existing Student object. It can use cls(...) to create and return a new instance. Using cls rather than writing Student(...) directly also allows subclasses to use the inherited method to create objects of their own class.

A static method is another method category. It is declared with @staticmethod and does not automatically receive either self or cls. It can be useful for a function that belongs conceptually with a class but does not need to access an instance or the class itself.


Built-in types are classes too

Classes and objects are not limited to programmer-defined types. Python’s built-in types are classes:

  • int is a class for integers.

  • str is a class for strings.

  • list is a class for lists.

  • dict is a class for dictionaries.

Calling a built-in type can create an object of that type. For example, int("50") creates an integer from a string. The expression type(50) reports that the value is an instance of the int class.

Strings and lists also have methods because they are objects. For example:

  • A string’s lower() method returns a lowercase version.

  • A string’s strip() method removes leading and trailing whitespace.

  • A list’s append() method adds an item to the list.

These methods were defined by Python’s authors. Programmer-defined classes use the same general structure: objects contain data and can support methods that operate on that data.


Inheritance

Inheritance lets a class reuse or extend the attributes and methods of another class. The class being inherited from is called the parent class or superclass; the class that inherits is the child class or subclass.

Suppose both students and professors are wizards, and both have a name. A Wizard class can hold the shared name validation and assignment:

class Wizard:
    def __init__(self, name):
        if not name:
            raise ValueError("Missing name")
        self.name = name

Student and Professor can inherit from Wizard while adding their own data:

class Student(Wizard):
    def __init__(self, name, house):
        super().__init__(name)
        self.house = house


class Professor(Wizard):
    def __init__(self, name, subject):
        super().__init__(name)
        self.subject = subject

Writing class Student(Wizard): declares Wizard as the parent class of Student. The call super().__init__(name) invokes the parent class’s initializer, so the shared name validation and assignment happen in one place. Each subclass can then add its own specialized attributes.

Inheritance is useful when classes share meaningful behavior or data. It avoids duplicating common code and represents a relationship in which a student is a kind of wizard and a professor is a kind of wizard.

A class can inherit through multiple levels, so a subclass can receive behavior from more distant ancestor classes as well as its immediate parent. Python also supports multiple inheritance, although class hierarchies can become more complicated when there is more than one parent.


Exception hierarchies and inheritance

Python’s built-in exceptions are organized in an inheritance hierarchy. For example, ValueError is a more specific kind of exception and inherits common behavior from broader exception classes.

This hierarchy allows programs to catch errors at different levels of generality:

  • Catching ValueError handles that particular type of invalid-value error.

  • Catching a broader parent exception can handle several related exception types.

  • Catching an overly broad exception can also hide errors that should be allowed to surface, so specific handling is generally clearer.

Programmers can define their own exception classes, often by inheriting from an existing exception class. This preserves useful behavior while allowing a program to describe a more specific kind of failure.


Operator overloading

Operator overloading allows a class to define what operators such as + mean for its objects. The same symbol can have different behavior for different types. In Python, + adds numbers, concatenates strings, and can combine certain sequences.

A class can define its own behavior for + with the special method __add__. For example, a vault might store three types of coins:

class Vault:
    def __init__(self, galleons=0, sickles=0, knuts=0):
        self.galleons = galleons
        self.sickles = sickles
        self.knuts = knuts

    def __str__(self):
        return (
            f"{self.galleons} galleons, "
            f"{self.sickles} sickles, "
            f"{self.knuts} knuts"
        )

    def __add__(self, other):
        galleons = self.galleons + other.galleons
        sickles = self.sickles + other.sickles
        knuts = self.knuts + other.knuts
        return Vault(galleons, sickles, knuts)

When Python evaluates:

total = potter + weasley

it calls the left-hand object’s __add__ method, passing the left operand as self and the right operand as other. The method can access both objects’ attributes, calculate the combined values, and return a new Vault.

Operator overloading is not limited to +; Python defines special methods for many operators and related operations. It gives a class a natural, consistent interface when the chosen operation makes conceptual sense. Overloading should reflect behavior that users of the class can reasonably understand—for example, adding two vaults to combine their contents.


Choosing when to use OOP

A class is useful when related data and behavior need a clear shared structure. It can represent a real-world or fictional entity, such as a student, professor, sorting hat, or vault, but classes are not limited to such entities.

Classes offer capabilities beyond basic containers:

  • They group related information and operations.

  • They standardize how objects are initialized.

  • They can validate data and raise exceptions when values are invalid.

  • They support inheritance and reusable behavior.

  • They can define custom string representations and operator behavior.

A tuple, list, dictionary, standalone function, module, or class may each be appropriate depending on the problem. For a short, simple task, a basic container or a few functions may be clearer than a class. As a program grows and its entities and behaviors become more interconnected, classes can help keep related code together and make the design easier to extend.

Object-oriented programming is therefore one tool in a programmer’s toolkit, rather than a requirement for every program.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent