Lesson 8
Making Objects the Main Star!
Chapter 7: Add robot actions!
Robot actions!
So far, you have a Robot
class with some attributes like id
, name
, position
and direction
.
Now that you have further knowledge about the power of methods, let’s put it to good use!
You will now refactor some of the functions in your robot project to become methods!
Step 1: Identify your methods
Firstly, take a look at your existing functions in your main.py
file. Can you identify any functions that can be potentially be a suitable Robot
‘s action? Good candidates would be those that have robot
as the input parameter and use attributes like robot.position
and robot.name
inside the function definition.
Also think about whether these make sense as methods? They should intuitively be some actions that you can imagine a robot doing.
Step 2: Convert functions to methods
Once you have identified the methods, move each function into the Robot
class definition and turn it into a method! Change all references of robot
to self
. Do this one at a time, and make sure your program is still working correctly each time.
There is no need to turn all functions into methods. Some are just better left as they are for now. We will continue to refactor your code in the next lesson.
This refactoring activity is somewhat of an art, and sometimes there might not even be a definite correct or incorrect answer. You will get better and faster in figuring out what makes a good method over time.
Have a quick try first, at least in identifying suitable methods for your Robot
class. You can then try converting one of the functions into a method in your class.
I will discuss my own thought process while going through this exercise myself in the next page. So feel free to read up after you have tried refactoring a bit to see whether you are on the right track!