We have seen how we can add a new method to an existing class, where we wanted to repair the robot so that it knew how to turn right. Here's another example of adding a method to an existing class.
class Amazing(RefurbishedRobot): def diag(self): self.set_trace_style(1, 'white') self.turn_left() self.move() self.turn_right() self.move() self.set_trace_style(1, 'sea green') Magician = Amazing() Magician.move() Magician.move() Magician.diag() Magician.diag() Magician.move() Magician.move() Magician.turn_off()
The new robot knows all the existing methods that the existing RefurbishedRobot knew [for example, move(), turn_off()] as well as a new one [diag()].
Sometimes, we want to create a new class that changes the basic behaviour of an existing one. To do so, we need to redefine a special method [__init__()]. The following example is such a case, where we "fix the oil leak", so that the new robot does not leave a trail. Actually, we do more than this as we have it leave a white trail (instead of a sea green one, which is the default), centered on the street or avenue where the robot moves [defined as style number 5] so that it effectively covers the grey dotted line, as though the robot was erasing it.
class Eraser(RefurbishedRobot): def __init__(self): RefurbishedRobot.__init__(self) self.set_trace_style(5, 'white') Sneaky = Eraser() while Sneaky.front_is_clear(): Sneaky.move() Sneaky.turn_off()
You may want to modify this to try other style numbers (1 to 5) with other colours.