Help support the author by donating or purchasing a copy of the book (not available yet)

Chapter 17 - Object Oriented Programming (OOP)

17.1 - Classes & Objects

So far we’ve met many of Pythons built-in types such as booleans, integers, dictionaries etc. These are all class types. This means that any particular instance of a string, list, float etc, is an object of the class string, list or float. In other words, every string object, e.g. "Hello", is an instance of the string class. An object is an implementation of a type

In this chapter we’re going to look at a programming paradigm called object oriented programming (OOP). This paradigm is based on the concept of objects, which contain data, in the form of attributes and functions (called methods).

In OOP, programs are designed by making them out of objects that interact with one another. An important feature of objects is that they use their methods to access and modify their attributes. For example, if we wanted to model a Person, they might have an age attributes and a name attribute. Each year they get one year older so they may have a change_age() method to update their age.

The general syntax for invoking an object’s method is object_name.method_name(arguments). We have done this multiple times. For example, calling the count() method on a string:

Most of the time, Python’s built-in types are not enough to model data we want, so we built our own types (or classes) which model the data exactly how we need.

A good way to think of this is that a class is a cookie cutter and an instance of that class is the cookie we cut out.

17.2 - Defining a new type

Let’s say we wanted to model Time. Python’s built in data types are not going to be enough, to easily and logically model this. Instead, we would create our own Time class. We define a new class using the class statement.

We have now defined a new class called time. As a side note, pass basically means “do nothing”. I have it there so our program will not crash.

Save the above code to a file called and import it as follows:

We can see that t is of type Time and t is an instance of Time and we can see it is an object stored at the memory location 0x000001A7C6902F60.

We want to represent time in hours, minutes, and seconds. We can therefore define a method that initialises the time of Time objects. We also want to define a display() method that will print out the time:

In the above class definition, the set_time() method requires four arguments. The first is the time object we want to initialise and the other three are the hours, minutes, and seconds we want to set for our time object.

As shown above, we access the hours, minutes and seconds attributes using the period operator e.g time_obj.hours = hours. This is saying, for the time object that was passed, set it’s hours attribute to the hours passed as an argument.

In the display() method, we access the hours, minutes, and seconds using the period operator.

Now let’s see how we can use this class:

We can see we have two different time objects. We create an object of the Time class by calling the class as if it were a function. Calling the class as a function will instantiate an instance of the class and return a reference to it.

17.3 - The self variable

As seen in the previous section, we had to call methods by referring to the class in which it belongs to e.g Time.display(t). However, we didn’t have to do that when invoking methods on Python’s built in types e.g s.count('a'). It turns out that this is just shorthand for str.count(s, 'a').

We can adopt the same approach for our Time class:

Note how we only have to pass three arguments to the set_time() method rather than the four we declared. This is because when we invoke an instance method on an object, that object is automatically passed as the first argument to the method. Therefore, we supply one less argument than the number we declared in the method definition. Python will automatically supply the missing object as the first argument on our behalf.

By convention, this first parameter, which we’ve been calling time_obj, is named self. This refers to the instance on which the method is acting. This makes the methods set_time() and display() instance methods.

Instance methods are methods that act upon a particular instance of an object. It’s first parameter is always the object upon which it will operate. By default, all a classes methods are instance methods unless we declare them as class methods which we will get to in a later chapter.

We can therefore re-write our class as follows:

And we can use it as follows:

I’m going to leave it at that for this chapter. There is a lot to take on here and it’s really important stuff! The rest of the book will be focused solely on object oriented programming. So, make sure you understand the material in this book and complete the following exercises.

17.4 - Exercises

Question 1

Write a class that models a Lamp. The lamp class will have have two methods. The first will initialise the lamp and is called plug_in(). This will set the is_on attribute which is a boolean to False. The second method is called toggle(). If the lamp is off, it will turn it on (set is_on to True) and if the lamp is on, it will turn it off (set is_on to True).

Your class may be imported and used as follows:

Question 2

Write a class that models a Cirlce. The circle class will have four methods. The first will initialise the circle. The initialise() method should take three parameters, x_coord, y_coord, and radius. This will set the circles x and y coordinates and it radius. The next method is called calc_area(). It should calculate the area of the circle (Look up the formula). The third method is called calc_perimeter() and should calculate the circumference of the circle (Look up the formula). The fourth method is overlaps(). It should take as an argument, another circle and print out whether or not the two circles overlap.

Your class may be imported and used as follows:

Hint: Your definition of the overlaps methods should be overlaps(self, other_circle)

Question 3

Write a class that models a students grades for particular modules. The class will have four methods. The first should initialise the student. The student should have a name and age. The grades should be modelled as a dictionary in which the key is the name of the module and the value is the grade. This should initially be empty. The second method is called add_module() and should add a module to the student object. The third is called update_module_grade() and should update the grade for a particular module. The final method is called show_grades() and should print out the students modules and the grade associated with each module.

Your class may be imported and used as follows:

Hint: Make sure you’re initialising the grades dictionary correctly!

Help support the author by donating or purchasing a copy of the book (not available yet)

Previous Chapter - Next Chapter