Topic 3: Object Oriented Programming

Introduction

From next week onwards we will move on to actually implementing some data structures in Python, starting with the stack and the linked list. However, in order to do this effectively and cleanly, you need to be familiar with object-oriented programming. You will be introduced to this topic in more depth in COM411 later, but I will introduce this week just enough object-oriented programming for you to be able to code your own data structures.

(Note that Python comes with an extensive range of built-in data structures, for example you can treat the standard list type as a stack and perform push and pop operations, but we are going to build them from scratch, in order to gain a deeper understanding of how the various data structures work.)

What is object-oriented programming? - A very quick summary

Object-oriented programming involves developing code by thinking about all the real-world entities that your program needs to handle (such as students, employees, or data structures such as linked lists and stacks) and writing code to represent each real-world entity. To do this, we need to create classes and objects.

Classes and Objects

See the Python documentation for classes and objects.

What is a class?

(This is a simplified explanation. More depth will be provided in COM411.)

A class can be thought of as a complex data type. Classes provide a way to define our own custom data structures. For example, we could create a Cat class to represent a cat, a Stack class to represent a stack, or a LinkedList class to represent a linked list. Classes represent specific types of real-world entity, such as cats, stacks or students, and can be considered as a blueprint which define how that type of entity works.

What is an object?

An object is a specific instance of a class, for example, a specific cat, stack or linked list. A class can be thought of as a blueprint, or specification, for how a particular data structure should work. However an object is a specific example of that data structure.

For example, each of the two cats in the photo below (Binnie and Clyde) could be represented in code with an object. One object for Binnie, and another for Clyde.

Cats

We could define a Cat class and then create many cat objects, reperesenting individual cats.

We could define a Stack class, and then create two Stack objects. One Stack object could be used in a web browser and contain your browsing history, whereas another could be used in a paint program and represent each drawing operation you do, allowing you to undo them.

Or, you could define a LinkedList class, and then have one LinkedList object to store students at a university, another to store courses, and yet another to store staff.

Attributes and methods

Classes and objects contain two key components:

To answer the question, you need to consider which of these are a general type of real-world entity and which are a specific real-world entity. Using this guidance we find that:

Implementing a Cat using a class

We will start with a simple class representing a cat. This should be saved in a separate file, containing only the class: cat.py.

class Cat:
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    def eat(self):
        self.weight += 1

This code does not create any actual cats. It just creates a class, or a blueprint or specification, for what cats are and what they do. Note, in particular, the following:

self.weight += 1

What does this do? Remember that self is the current object, in other words the current cat. The operator += increases a variable by one. So self.weight += 1 will increase the weight of the current cat by one.

To create actual cats, we need to create Cat objects, as follows. This should be in a separate file, main.py. Note how we import the Cat class from cat.py.

from cat import Cat

cat1 = Cat("Binnie", 4)
cat2 = Cat("Clyde", 2)
cat1.eat()
cat2.eat()
print(cat1.weight)
print(cat2.weight)

This code creates two specific cats, cat1 and cat2. The lines:

cat1 = Cat("Binnie", 4)
cat2 = Cat("Clyde", 2)

actually create the two cats. In each case, the initialisation method __init__(), which we saw above, is called, and the data about that cat is passed into the object.

Next, we actually make the cats do something by calling methods. Firstly, we call the eat() method on each cat:

cat1.eat()
cat2.eat()

We then print the weight of each cat, to show that eating has increased the weight by one:

print(cat1.weight)
print(cat2.weight)

Methods with Parameters

class Cat:
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    def eat(self, amount):
        self.weight += amount

In many cases, we need to pass information in to a method to tell it what to do. For example, it would be useful if we could tell the eat() how much food the cat needs to eat. We do this by specifying one or more parameters in the method, separated by commas. So:

def eat(self, amount)

includes a parameter amount specifying how much food the cat should eat. We then use that in our statement to increase the weight, by increasing it by amount:

self.weight += amount

When calling the method, we then specify the parameter, e.g:

cat1 = Cat("Flathead", 4)
cat2 = Cat("Cupra", 3)
cat1.eat(3)
cat2.eat(2)
print(cat1.weight)
print(cat2.weight)

Coding Exercise 3.1

  1. Try out this example. Save your Cat class in one file, cat.py. Add the code which creates two Cat objects and makes them eat (see above) into your main.py and import the Cat class into your main.py using:
    from cat import Cat
    Assuming your Cat class is in the file cat.py, this will import the Cat class into your main.py.
  2. Once it's working, do the following:
    • Add some other attributes to the Cat class, which you think would be appropriate for a Cat class to have.
    • Add a print() method to display all the details of the Cat using a print() statement.
    • Create a walk() method inside the Cat class. This should reduce the cat's weight by one.
    • In the section of your code which creates the cats, create a third cat, "Old Tom" with weight 6, and print all three cats by calling their print() method.
    • Make Old Tom eat, and make all three cats walk after they have eaten. After walking, display all three cats' weight again, to show that walking reduces the weight by one.
  3. Using an if statement, change the walk() method so that the cat cannot walk if the weight is below 1. (The intention is to avoid starving the cat).

Coding Exercise 3.2: Additional object-oriented programming exercise

Try out this additional exercise using classes and objects.

  1. Create a completely new class called Student to represent a student. Pass the following as parameters to the __init__() method, and initialise the appropriate attributes.
    • id, representing the student's ID
    • name, representing the student's name
    • course, representing the student's course
    • mark, the student's mark
  2. Give the Student class a print() method, which prints the student details.
  3. Write some code to create 5 students within a for loop. Create a Student object each time the loop runs, using details the user entered from the keyboard using the input statement . Then, still within the loop, display each student by printing it.
  4. Add a setMark() method to your Student class, to set the student's mark. The method must validate the mark using an if statement, and check that it is between 0 and 100. The mark should only be updated if it is valid. Return a boolean to indicate whether the method was successful or not: it should return True if the mark was valid and False otherwise.
  5. Add a printGrade() method to Student. This should print the student's grade as a string based on the mark, according to this scheme :
    • 70+ : First
    • 60-69 : 2/1
    • 50-59 : 2/2
    • 40-49 : Third
    • 0-39 : Fail
  6. Test out the previous question by modifying the loop so that you call the printGrade() method of each student you create.