Programming techniques and object-oriented programming · A level · OCR H446 1.2.4, AQA 7517 4.1.2.3, Eduqas A500QS 1.4 · about 20 min
Classes, objects, attributes, methods and constructors; encapsulation, access specifiers, getters and setters, and class diagrams.
[1 mark]What is instantiation?
[1 mark]What does this program print?
class Counter:
def __init__(self, start):
self.__count = start
def up(self):
self.__count = self.__count + 1
return self.__count
a = Counter(0)
b = Counter(10)
a.up()
a.up()
print(a.up(), b.up())[1 mark]In a class diagram, what does the symbol - before an attribute mean?
[1 mark]Which are reasons for making an attribute private and providing a setter method?
Tick every answer that is true.
[1 mark]What is the name of the method that runs automatically when an object is created, to give its attributes their starting values?
Write the class Odometer from the class diagram.
- The constructor __init__(self, name) stores name (a string) in the private attribute self.__name and sets the private attribute self.__total to 0.
- drive(self, cm) takes a whole number of cm. If cm is 0 or more it drives forward cm; if it is negative it drives backward by -cm. Either way it adds the size of the move, abs(cm), to self.__total.
- get_total(self) returns the total.
- report(self) returns the string <name>: <total> cm.
Then make two objects, trip_a = Odometer("trip A") and trip_b = Odometer("trip B"), and call trip_a.drive(20), trip_b.drive(-10) and trip_a.drive(15) in that order. Print trip_a.report() then trip_b.report(), which should show trip A: 35 cm and trip B: 10 cm.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
class Odometer:
def __init__(self, name):
self.__name = name
trip_a = Odometer("trip A")Plan your program here, then type it in and press Run.
reset(self). Should it be public or private? Draw the new class diagram.print(trip_a.__total) outside the class. Then try print(trip_a._Odometer__total). What does that tell you about how private Python's privacy is?ValueError.