This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: Objectify your robot!

Robot class

face Josiah Wang

Last time, you refactored your robot by representing a robot instance as a dict representation with some keys like "name", "id". "position" and "direction" (or something similar).

Following up from that, let us now refactor your robot project (yet again!)

This time, you will create a class Robot to represent your robot, rather than a dict. The ‘conversion’ should not take too long, since your dict representation should already be quite close to a Robot object.

Task 1: Define Robot class

Your first task is to define your new Robot class.

Your existing main.py has also become quite large. To make it easier for you in the future, define your Robot class in a separate file as a module. I will call the file robot.py. You might have something like the following in robot.py (I am using identifier because id is a built-in Python function and I do not want to mess things up. It is ok to use it as an attribute though).

class Robot:
    def __init__(self, identifier, name, position, direction):
        self.id = identifier
        self.name = name
        ...

Task 2: Convert dict to Robot instances

Now, go into main.py (or equivalent).

The first thing you should do is to import your robot module. I recommend importing the class directly as below, since you might have used robot as a variable in your code like me!

from robot import Robot

Then go through main.py and convert any dict initialisation of your robot to use Robot constructors instead.

You can then change any references of robot["id"] to robot.id, etc. You can use the find and replace function of your text editor to help speed up the process.

Make sure that the code works correctly before moving on.

Please do not commit your changes yet - you will do this on the next page!