Blackboard Exercise 6: Worked solutions
Algorithms, Programming, and Data Representation · Module 92313 · Blackboard Exercise 6
Exercise 6.1: Objects, classes and methods
Read the shared vector class, then distinguish a class definition from the state and behaviour of each instance.
Connected topics: Classes and instances (§10.2) · Methods and self (§10.4)
Use this class for all five parts. The two instances in parts 2–4 are v1 = Vector2D(3, 4) and v2 = Vector2D(6, 8).
class Vector2D(object):
def __init__(self, x, y):
self.x = x
self.y = y
def length(self):
return (self.x**2 + self.y**2)**0.5
def __str__(self):
return "<" + str(self.x) + "," + str(self.y) + ">"6.1.1 Name the class components
Try first: Mark the class line, the assignments to the instance, and each method signature.
Attempted it? Open the worked steps
6.1.1 Name the class components
The class is
Vector2D. The instance attributes arexandy, created by assignments toself.xandself.y.Its methods are
__init__,lengthand__str__.__init__is the constructor initializer, andselfis the parameter referring to the current instance. Check: all three method signatures begin withself.
6.1.2 Predict the printed values
Find the output of print(v1), print(v1.length()) and print(v2.length()).
Try first: Trace the stored coordinates through __str__ and length without running the code.
Attempted it? Open the worked steps
6.1.2 Predict the printed values
For
v1,__str__joins 3 and 4 without spaces to give<3,4>. The length is (3² + 4²)0.5 = 5.0.For
v2, the length is (6² + 8²)0.5 = 10.0. The threeprintcalls therefore output:<3,4> 5.0 10.0Check: the second vector doubles both coordinates, so its length doubles from 5.0 to 10.0.
6.1.3 Type or instance?
Try first: Ask whether both variables were constructed by the same class.
Attempted it? Open the worked steps
6.1.3 Type or instance?
v1andv2are different objects (instances) of the same type,Vector2D. Their coordinates also differ.Check:
type(v1) is type(v2)is true, whilev1 is v2is false. Equal types do not imply identical objects.
6.1.4 Compare bound and class method calls
Try first: Account for the first argument in each way of calling length.
Attempted it? Open the worked steps
6.1.4 Compare bound and class method calls
v1.length()looks up the function on the class and bindsv1asselfautomatically.Vector2D.length(v1)calls that same function through the class and passesv1explicitly. Both evaluate the length ofv1and return 5.0.
6.1.5 Implement distance
Add distance(self, other) to Vector2D so it returns the Euclidean distance between two vectors.
Try first: Subtract coordinates before applying the same square-root pattern as length.
Attempted it? Open the worked steps
6.1.5 Implement distance
For two points, the horizontal and vertical differences are
self.x - other.xandself.y - other.y. Square both, add, and take the square root.def distance(self, other): dx = self.x - other.x dy = self.y - other.y return (dx**2 + dy**2)**0.5Add this method to
Vector2D. Fora = Vector2D(1, 2)andb = Vector2D(4, 6), the differences are −3 and −4, givinga.distance(b) == 5.0. The distance is unchanged if the call is reversed.
Exercise 6.2: Information hiding
Test what direct attribute access can break, then add a guarded withdrawal.
Connected topics: Getters and information hiding (§11.2) · Initialisation and attributes (§10.3)
Use this account class. Assume balances and transaction amounts are numeric.
class Account(object):
def __init__(self, balance):
self.balance = balance
def get_balance(self):
return self.balance
def deposit(self, amount):
self.balance += amount6.2.1 Explain three direct assignments
Evaluate a.balance = -500, a.balance = "a lot" and a.currency = "EUR" after a = Account(100).
Try first: Consider which states the class currently accepts without validation.
Attempted it? Open the worked steps
6.2.1 Explain three direct assignments
After
a = Account(100),a.balance = -500permits a negative balance, bypassing any withdrawal rule.a.balance = "a lot"changes the value to text, so later arithmetic such asdepositmay fail.a.currency = "EUR"creates an extra attribute even though the class never established how it relates to the balance. These assignments succeed in ordinary Python; the problem is that they can violate the intended account model.
6.2.2 Implement a guarded withdrawal
Add withdraw(self, amount); accept only a positive amount at most the current balance, leave the balance unchanged on failure, and return a Boolean.
Try first: Check both restrictions before mutating the balance.
Attempted it? Open the worked steps
6.2.2 Implement a guarded withdrawal
A withdrawal is valid only when
0 < amount <= self.balance. Reject every other numeric amount first, including a NaN value for which that comparison is false.def withdraw(self, amount): if not (0 < amount <= self.balance): return False self.balance -= amount return TrueFrom a balance of 100,
withdraw(0),withdraw(-1)andwithdraw(101)returnFalseand leave 100 unchanged;withdraw(40)returnsTrueand leaves 60. This assumes numeric inputs, as in the supplied class.
6.2.3 Adapt callers to an internal rename
Compare print(a.balance) and print(a.get_balance()) after the internal field changes to self.amount.
Try first: Separate use of a public method from use of a stored field.
Attempted it? Open the worked steps
6.2.3 Adapt callers to an internal rename
If storage is renamed from
self.balancetoself.amountandget_balance()is updated,print(a.balance)fails because the old attribute no longer exists.print(a.get_balance())still works and does not need changing. Replace the direct-access caller with that method call; the method is the stable interface despite the internal rename.
6.2.4 Explain getters and setters
Try first: Identify where validation can happen when callers use methods.
Attempted it? Open the worked steps
6.2.4 Explain getters and setters
A getter provides a stable way to read account state; a setter or action method can validate a proposed change before storing it. Callers need not know whether the value is held in
balanceoramount.Check the limit: Python still allows ordinary public attributes to be assigned directly. Information hiding here is an interface discipline, not enforced privacy by these methods alone.
Exercise 6.3: Classes and inheritance
Trace constructor calls and method lookup through three classes.
Connected topics: Inheritance and method lookup (§11.4) · Extending and overriding (§11.5)
Use the following hierarchy for all seven parts. Let s = Square('S1', 5).
class Shape(object):
def __init__(self, name):
self.name = name
def describe(self):
return "Shape: " + self.name
class Rectangle(Shape):
def __init__(self, name, width, height):
Shape.__init__(self, name)
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Square(Rectangle):
def __init__(self, name, side):
Rectangle.__init__(self, name, side, side)
def describe(self):
return "Square: " + self.name6.3.1 Draw the class hierarchy
Try first: Follow each parent named in parentheses.
Attempted it? Open the worked steps
6.3.1 Draw the class hierarchy
Rectangle(Shape)makesShapethe direct parent ofRectangle.Square(Rectangle)makesRectanglethe direct parent ofSquare.Shape ↑ Rectangle ↑ SquareThe arrows point from subclass to its immediate parent, so method lookup from a square moves upward through rectangle, then shape.
6.3.2 Find each member’s provider
For s, identify where name, width, height, area() and describe() come from.
Try first: Trace constructor assignments separately from method lookup.
Attempted it? Open the worked steps
6.3.2 Find each member’s provider
Square.__init__callsRectangle.__init__, which callsShape.__init__. Thuss.nameis assigned byShape;s.widthands.heightare assigned byRectangle. All three values live ons.s.area()usesRectangle.area;s.describe()usesSquare.describe. Check:Squaredefinesdescribeitself, so lookup stops there.
6.3.3 Predict the output
Find print(s.area()) and print(s.describe()).
Try first: Substitute the side length into the inherited area method.
Attempted it? Open the worked steps
6.3.3 Predict the output
Square.__init__passes side 5 as both width and height.Rectangle.areamultiplies them to obtain 25.Square.describeprefixes the stored name withSquare:. The outputs are:25 Square: S1
6.3.4 Explain inherited area
Try first: Follow the lookup path when Square lacks the method.
Attempted it? Open the worked steps
6.3.4 Explain inherited area
Python first looks for
areaonSquare. It is absent, so lookup continues to the parentRectangleand findsRectangle.area.The inherited function is bound to
s, so itsself.widthandself.heightread the square’s own values. Check: it returns 25.
6.3.5 Explain the overridden description
Try first: Compare method lookup on a square with lookup on a plain shape.
Attempted it? Open the worked steps
6.3.5 Explain the overridden description
Squaredefines its owndescribe, so lookup finds it before reachingShape.describe. This is overriding.Therefore
s.describe()returnsSquare: S1; a plainShape("S1").describe()would instead returnShape: S1.
6.3.6 Add a string form to Rectangle
Make Rectangle('R1', 4, 7) print Rectangle R1: 4 x 7.
Try first: Return a string rather than printing inside __str__.
Attempted it? Open the worked steps
6.3.6 Add a string form to Rectangle
The object already stores
name,widthandheight. Format them in the requested order.def __str__(self): return f"Rectangle {self.name}: {self.width} x {self.height}"Place this method inside
Rectangle. Thenprint(Rectangle('R1', 4, 7))displaysRectangle R1: 4 x 7.
6.3.7 Check inherited string conversion
Try first: Look for __str__ on Square before moving to Rectangle.
Attempted it? Open the worked steps
6.3.7 Check inherited string conversion
Squaredefines no__str__, so it inheritsRectangle.__str__automatically.After adding the method in 6.3.6,
print(s)displaysRectangle S1: 5 x 5. That wording may be surprising for a square; Square would need its own override to change the label.
Exercise 6.4: Find the bugs
Diagnose signatures, missing attributes, constructor chaining, and string conversion in a broken class pair.
Connected topics: Methods and self (§10.4) · Extending and overriding (§11.5)
This intentionally faulty program should create a student and print the age, semester and object:
class Person(object):
def __init__(name, age):
self.name = name
age = age
def get_age():
return self.age
def __str__(self):
print(self.name + ": " + str(self.age))
class Student(Person):
def __init__(self, name, age, semester):
self.semester = semester
def get_semester(self):
return semester
s = Student("Anna", 22, 3)
print(s.get_age())
print(s.get_semester())
print(s)6.4.1 Locate every error
Try first: Check method signatures, assignments to the instance, inherited initialisation, names in scope and __str__ return values.
Attempted it? Open the worked steps
6.4.1 Locate every error
Person.__init__lacksself; a normal call through an instance receives the instance plus the supplied name and age, causing an argument-count error. Its body also refers to undefinedselfandage = agedoes not createself.age.get_agelacksselfand then refers to undefinedself.Person.__str__prints instead of returning a string. Whenprint(s)requests that string, Python getsNonefrom__str__and raises a TypeError.Student.__init__never calls the parent initializer, leavingnameandageunset even after Person is repaired.get_semesterreturns an unbound local name; it must readself.semester. Check all fixes against the three intended print calls.
6.4.2 Correct the implementation
Try first: Repair Person once and reuse its initializer from Student.
Attempted it? Open the worked steps
6.4.2 Correct the implementation
Give each instance method a
selfparameter, assign the age to the instance, and return a string from__str__.class Person(object): def __init__(self, name, age): self.name = name self.age = age def get_age(self): return self.age def __str__(self): return f"{self.name}: {self.age}" class Student(Person): def __init__(self, name, age, semester): super().__init__(name, age) self.semester = semester def get_semester(self): return self.semesterWith
s = Student("Anna", 22, 3), the three calls output22,3andAnna: 22on separate lines. Person’s attributes are set once by its own initializer.
6.4.3 Explain parent initialisation
Try first: List the state supplied by Person and used by the inherited methods.
Attempted it? Open the worked steps
6.4.3 Explain parent initialisation
Person.__init__establishesnameandageon the Student object. Inheritedget_ageand__str__expect those attributes.Calling
super().__init__(name, age)keeps that setup in one place; otherwise the child would duplicate it or leave the inherited methods broken.
6.4.4 State the __str__ contract
Try first: Separate producing a representation from displaying one.
Attempted it? Open the worked steps
6.4.4 State the __str__ contract
__str__must return a string.print(s)asksstr(s)for that string and then writes it to the output stream.If
__str__only callsprint, it returnsNoneimplicitly. Python then raisesTypeErrorbecause the result is not a string; a side-effecting print cannot replace the return value.
Exercise 6.5: Class variables
Track a counter shared by all items and IDs stored separately on each object.
Connected topics: Class variables and IDs (§11.6) · Initialisation and attributes (§10.3)
Use this class, starting with Item.counter == 0:
class Item(object):
counter = 0
def __init__(self, name):
Item.counter += 1
self.name = name
self.id = Item.counter6.5.1 Predict the IDs and counter
Find print(a.id), print(b.id), print(c.id) and print(Item.counter).
Try first: Trace the shared counter after constructing A, B and C.
Attempted it? Open the worked steps
6.5.1 Predict the IDs and counter
Each construction increments
Item.counteronce, then copies its current value into the new instance’sid. The IDs become 1, 2 and 3.After
a = Item("A"),b = Item("B")andc = Item("C"), the four prints produce:1 2 3 3Check: the last value is the class counter, not the ID of a fourth object.
6.5.2 Classify the attributes
Try first: Inspect where each name is assigned.
Attempted it? Open the worked steps
6.5.2 Classify the attributes
counteris a class variable because it is defined in the class body and updated asItem.counter. Every Item construction sees that shared value.nameandidare instance variables because the initializer stores them asself.nameandself.id. Check: the three objects retain different IDs whileItem.counteris 3.
6.5.3 Explain the shared counter
Try first: Compare a shared count with a count reset for each new object.
Attempted it? Open the worked steps
6.5.3 Explain the shared counter
A class variable keeps one sequence across all Item instances. Every constructor reads and increments the same
Item.counter, so each newly assignediddiffers.If each new instance started its own counter at zero, every first increment would give 1. The IDs would collide.
6.5.4 Format a three-digit ID
Add get_id() so the first and tenth items return "001" and "010".
Try first: Convert the stored integer to text and pad on the left.
Attempted it? Open the worked steps
6.5.4 Format a three-digit ID
The numeric
idis already stored on each instance; formatting should not change it.def get_id(self): return str(self.id).zfill(3)For IDs 1 and 10, the results are
"001"and"010". Check: the method returns text, whileself.idstays an integer.
Exercise 6.6: Working with your own types
Use Python’s special methods to make a fraction class support arithmetic and equality.
Connected topics: Fraction objects (§10.7) · Types and special methods (§10.6)
Assume each denominator is nonzero. Start with this class; the operator methods are to be added inside it.
class Fraction(object):
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return str(self.numerator) + "/" + str(self.denominator)6.6.1 Implement fraction addition
Make Fraction(1, 2) + Fraction(1, 3) print 5/6.
Try first: Use cross-products for the new numerator and multiply the denominators.
Attempted it? Open the worked steps
6.6.1 Implement fraction addition
If the first fraction is a over b and the second is c over d, the sum has numerator
a*d + b*cand denominatorb*d. The result should be a new Fraction rather than changing either operand.def __add__(self, other): numerator = self.numerator * other.denominator + other.numerator * self.denominator denominator = self.denominator * other.denominator return Fraction(numerator, denominator)Fraction(1, 2) + Fraction(1, 3)createsFraction(5, 6), which prints5/6. Check by hand: 1·3 + 1·2 = 5 and 2·3 = 6.
6.6.2 Compare equivalent fractions
Make mathematically equal fractions compare equal even if their stored fields differ; avoid floating-point division.
Try first: Cross-multiply without converting to floats.
Attempted it? Open the worked steps
6.6.2 Compare equivalent fractions
With nonzero denominators,
a/b == c/dexactly whena*d == c*b. This also works when the stored numerator and denominator are not simplified.def __eq__(self, other): if not isinstance(other, Fraction): return NotImplemented return self.numerator * other.denominator == other.numerator * self.denominatorFraction(1, 2) == Fraction(2, 4)isTruebecause 1·4 = 2·2. ReturningNotImplementedfor an unrelated type lets Python’s equality protocol decide the fallback.
6.6.3 Identify self and other in addition
Try first: Read the expression from the left operand’s method call.
Attempted it? Open the worked steps
6.6.3 Identify self and other in addition
In
f1 + f2, Python first invokesf1.__add__(f2). Thusselfisf1andotherisf2.Check: the cross-products in 6.6.1 read fields from both objects, and the new result does not overwrite either input.
6.6.4 Name the addition result type
Try first: Connect the operator method to the expression that consumes its result.
Attempted it? Open the worked steps
6.6.4 Name the addition result type
__add__should return a newFractioninstance holding the sum’s numerator and denominator.A string such as
"5/6"would print similarly but could not be added as a Fraction again. Check:(Fraction(1, 2) + Fraction(1, 3)).numeratoris 5.
6.6.5 Compare addition with equality
Try first: Identify the invoked method and its output type for each operator.
Attempted it? Open the worked steps
6.6.5 Compare addition with equality
f1 + f2calls__add__and, in this class, returns a newFractionvalue. Its string form is used only when the result is printed.f1 == f2calls__eq__and returns a Boolean comparison result for Fraction operands. Check: the first result can participate in further fraction arithmetic; the second answers a yes-or-no question.
Personal worked solutions based on APDR Blackboard Exercise 6. Prompts and explanations are rewritten in my own words; short source programs are shown where needed to attempt the tasks. No exercise-sheet prose or figures are reproduced. Not an official FAU publication; check course details against current materials. Made by Thanate Amornjiraporn (Focus).