Object oriented programming

By Martin McBride, 2018-10-19
Tags: classes
Categories: object oriented programming

Object oriented programming is one of several programming paradigms that Python supports.

What is OOP?

In traditional procedural programming, a program usually consists of a set of functions (ge func1, func2, func3), and some variables that hold data (eg x, y, z):

The problem here is that any function can call any other function, and any function can access any variable. This is ok for small, simple programs, but if you try to write a very large program, with more than one programmer working in the code, it can become quite difficult to control.

In Python we might try to solve this problem by using modules. In a module we put related functions and data into a separate file. Each module can be developed and documented separately, and if you want to use a module you must explicitly import it into your code.

In object oriented programming, we take this one stage further. We identify "things" in our program and represent them as objects. An object contains all the data and the functions that are required to represent that thing, all contained together in one structure. This is called encapuslation.

Examples of objects

You will already have worked with objects in Python. Strings, lists, tuples, and dictionaries are all examples of objects.

Here are some example objects:

x = [1, 2, 3]
y = [10, 11, 12, 13]
z = 'abc'


s = z.upper()

n = x.index(2)
m = z.index('a')

An object has 4 main attributes:

  • Type. In this example, x and y are of type list, z is of type string. Every object must have a type.
  • Data. This depends on the type. A list contains an ordered set of values. A contains consists of an ordered set of characters. Other types store different data.
  • Methods. Lists and strings each have many different methods. You can append a value to a list, you can use upper to convert a string to upper case, and you can use index with either a list or a string to find the location of an element.
  • Identity. Each object is a unique and independent. So for example, although x amd y both have type list, they are different lists. Appending a new value to the list x has no effect on the list y.

Generally, the type of an object tells you what sort of data it stores, and which methods it supports.

When you create an actual object of a particular type, you add its own unique data.

Note that we don't necessarily know exactly how each object stores its data. That is quite deliberate, and is called data encapsulation (or sometimes data hiding or information hiding). The idea is that you should only access the object by its methods. That way, if Python decides to implement object in a different way (perhaps to make it more efficient), provided the methods don't change, your code will still work.


In Python you can define your own object types. User defined types are called classes. A class is just a particular sort of type.

It is important to understand the distinction between classes and objects. For example the following code defines a Person class that stores the details of a person:

class Person:

    def __init__(self, title, forename, surname):
        self.title = title
        self.forename = forename
        self.surname = surname

This class has 3 data members: title, forename, and surname. It has one method, __init__, that in effect defines how we create the object. This is explained in the next sections .

This code defines a class, but it doesn't create any actual objects. Here is the code to create a set of 3 Person objects:

p1 = Person('Mr', 'John', 'Smith')
p2 = Person('Ms', 'Mary', 'Brown')
p3 = Person('Mr', 'David', 'Jones')

If we want to define more data members and methods, we must add them to the class definitions.

Identifying classes

The main point of OOP is to decompose your program into smaller parts so that it is easier to design, write, and maintain. This normally works best if your objects represent "things" that your program deals with. That way you can easily understand what each object does. If the objects represent things in your program, then classes must represent types of thing in your program. Here are some concrete examples of the sorts of classes you might use in a couple of different situations:

File handling

File handling code will often uses a class that represents a file path (such as "c:\temp\myfile.txt"). This might be a simple string object, or it might be a special object with extra methods (for example, methods to obtains the file extension).

You would also need a class that represents an actual file, after it has been opened. It will have methods to read and write data from the file.

You might even have a class that represents a folder tree, which for example allows you to find all the *.png files in your home folder including all subfolders.

GUI programming

If you are writing a GUI application you will use classes that represent the different elements of the UI - windows, panes, buttons, menus etc. They will have methods controlling their colour, position, text content etc.

If you program edits some kind of document, you will also have classes that represent the contents of the document, with method that allow you to load and save the document to file, fetch or update parts of the document, etc.

You will also use classes to allow the GUI and document to interact. For example you might use observer classes (sometimes called listeners) that are called when the user clicks a button or menu item etc in the UI, and causes some change in the document.

Don't be concerned of you end up using a lot of classes. A typical desktop application, for example, might contain hundreds or thousands of classes.

See also

If you found this article useful, you might be interested in the book NumPy Recipes or other books by the same author.

Join the PythonInformer Newsletter

Sign up using this form to receive an email when new content is added:

Popular tags

2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest