Programming techniques and object-oriented programming · A level · OCR H446 1.2.4, AQA 7517 4.1.2.3, Eduqas A500QS 1.4 · about 25 min
Subclasses and super, overriding, polymorphism, and abstract, virtual and static methods, with robot behaviours as subclasses.
[1 mark]What does this program print?
class Robot:
def __init__(self, name):
self.name = name
def greet(self):
return "I am " + self.name
class Rover(Robot):
def greet(self):
return super().greet() + " and I rove"
class Drone(Robot):
pass
for r in [Rover("R1"), Drone("D1")]:
print(r.greet())[1 mark]What is polymorphism?
[1 mark]What is true of an abstract class?
[1 mark]A static method is called as Motor.clamp(120). What can it not do?
[1 mark]Inheritance models which relationship between a subclass and its superclass? Answer with two words.
The starter has the superclass Behaviour, with a name attribute and an act() method. Write three subclasses from the class diagram. Each constructor calls super().__init__ with the behaviour's name, and each overrides act() so that it does its job and then prints <name> done:
- Chirp(note): name chirp; stores note (a frequency in Hz) and its act plays that note twice, 0.2 seconds each time.
- Square(size): name square; stores size (cm) and its act drives a square with sides of size cm, turning right 90 degrees at each corner.
- Spin(): name spin; its act turns right a full 360 degrees.
Then make the list routine = [Chirp(523), Square(20), Spin(), Chirp(784)] and call act() on each object in order with one loop. Do not use isinstance or type: polymorphism chooses the method.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
class Behaviour:
def __init__(self, name):
self.name = name
def act(self):
print(self.name, "does nothing")
routine = [Behaviour("chirp"), Behaviour("square")]
for behaviour in routine:
behaviour.act()Plan your program here, then type it in and press Run.
Pause(seconds) subclass that does not override act. What does it print, and why?Behaviour abstract with Python's abc module and @abstractmethod. What happens now when you try Behaviour("test")?Polygon(sides, size) subclass, then make Square a subclass of Polygon. How much of Square is left?