APDR

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.

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

  1. The class is Vector2D. The instance attributes are x and y, created by assignments to self.x and self.y.

  2. Its methods are __init__, length and __str__. __init__ is the constructor initializer, and self is the parameter referring to the current instance. Check: all three method signatures begin with self.

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

  1. For v1, __str__ joins 3 and 4 without spaces to give <3,4>. The length is (3² + 4²)0.5 = 5.0.

  2. For v2, the length is (6² + 8²)0.5 = 10.0. The three print calls therefore output:

    <3,4>
    5.0
    10.0
  3. Check: 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?

  1. v1 and v2 are different objects (instances) of the same type, Vector2D. Their coordinates also differ.

  2. Check: type(v1) is type(v2) is true, while v1 is v2 is 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

  1. v1.length() looks up the function on the class and binds v1 as self automatically.

  2. Vector2D.length(v1) calls that same function through the class and passes v1 explicitly. Both evaluate the length of v1 and 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

  1. For two points, the horizontal and vertical differences are self.x - other.x and self.y - other.y. Square both, add, and take the square root.

  2. def distance(self, other):
        dx = self.x - other.x
        dy = self.y - other.y
        return (dx**2 + dy**2)**0.5
  3. Add this method to Vector2D. For a = Vector2D(1, 2) and b = Vector2D(4, 6), the differences are −3 and −4, giving a.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.

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 += amount

6.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

  1. After a = Account(100), a.balance = -500 permits a negative balance, bypassing any withdrawal rule. a.balance = "a lot" changes the value to text, so later arithmetic such as deposit may fail.

  2. 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

  1. 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.

  2. def withdraw(self, amount):
        if not (0 < amount <= self.balance):
            return False
        self.balance -= amount
        return True
  3. From a balance of 100, withdraw(0), withdraw(-1) and withdraw(101) return False and leave 100 unchanged; withdraw(40) returns True and 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

  1. If storage is renamed from self.balance to self.amount and get_balance() is updated, print(a.balance) fails because the old attribute no longer exists.

  2. 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

  1. 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 balance or amount.

  2. 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.

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.name

6.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

  1. Rectangle(Shape) makes Shape the direct parent of Rectangle. Square(Rectangle) makes Rectangle the direct parent of Square.

  2. Shape
      ↑
    Rectangle
      ↑
    Square
  3. The 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

  1. Square.__init__ calls Rectangle.__init__, which calls Shape.__init__. Thus s.name is assigned by Shape; s.width and s.height are assigned by Rectangle. All three values live on s.

  2. s.area() uses Rectangle.area; s.describe() uses Square.describe. Check: Square defines describe itself, 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

  1. Square.__init__ passes side 5 as both width and height. Rectangle.area multiplies them to obtain 25.

  2. Square.describe prefixes the stored name with Square: . 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

  1. Python first looks for area on Square. It is absent, so lookup continues to the parent Rectangle and finds Rectangle.area.

  2. The inherited function is bound to s, so its self.width and self.height read 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

  1. Square defines its own describe, so lookup finds it before reaching Shape.describe. This is overriding.

  2. Therefore s.describe() returns Square: S1; a plain Shape("S1").describe() would instead return Shape: 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

  1. The object already stores name, width and height. Format them in the requested order.

  2. def __str__(self):
        return f"Rectangle {self.name}: {self.width} x {self.height}"
  3. Place this method inside Rectangle. Then print(Rectangle('R1', 4, 7)) displays Rectangle 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

  1. Square defines no __str__, so it inherits Rectangle.__str__ automatically.

  2. After adding the method in 6.3.6, print(s) displays Rectangle 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.

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

  1. Person.__init__ lacks self; 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 undefined self and age = age does not create self.age.

  2. get_age lacks self and then refers to undefined self. Person.__str__ prints instead of returning a string. When print(s) requests that string, Python gets None from __str__ and raises a TypeError.

  3. Student.__init__ never calls the parent initializer, leaving name and age unset even after Person is repaired. get_semester returns an unbound local name; it must read self.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

  1. Give each instance method a self parameter, assign the age to the instance, and return a string from __str__.

  2. 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.semester
  3. With s = Student("Anna", 22, 3), the three calls output 22, 3 and Anna: 22 on 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

  1. Person.__init__ establishes name and age on the Student object. Inherited get_age and __str__ expect those attributes.

  2. 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

  1. __str__ must return a string. print(s) asks str(s) for that string and then writes it to the output stream.

  2. If __str__ only calls print, it returns None implicitly. Python then raises TypeError because 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.

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.counter

6.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

  1. Each construction increments Item.counter once, then copies its current value into the new instance’s id. The IDs become 1, 2 and 3.

  2. After a = Item("A"), b = Item("B") and c = Item("C"), the four prints produce:

    1
    2
    3
    3
  3. Check: 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

  1. counter is a class variable because it is defined in the class body and updated as Item.counter. Every Item construction sees that shared value.

  2. name and id are instance variables because the initializer stores them as self.name and self.id. Check: the three objects retain different IDs while Item.counter is 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

  1. A class variable keeps one sequence across all Item instances. Every constructor reads and increments the same Item.counter, so each newly assigned id differs.

  2. 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

  1. The numeric id is already stored on each instance; formatting should not change it.

  2. def get_id(self):
        return str(self.id).zfill(3)
  3. For IDs 1 and 10, the results are "001" and "010". Check: the method returns text, while self.id stays an integer.

Exercise 6.6: Working with your own types

Use Python’s special methods to make a fraction class support arithmetic and equality.

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

  1. If the first fraction is a over b and the second is c over d, the sum has numerator a*d + b*c and denominator b*d. The result should be a new Fraction rather than changing either operand.

  2. def __add__(self, other):
        numerator = self.numerator * other.denominator + other.numerator * self.denominator
        denominator = self.denominator * other.denominator
        return Fraction(numerator, denominator)
  3. Fraction(1, 2) + Fraction(1, 3) creates Fraction(5, 6), which prints 5/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

  1. With nonzero denominators, a/b == c/d exactly when a*d == c*b. This also works when the stored numerator and denominator are not simplified.

  2. def __eq__(self, other):
        if not isinstance(other, Fraction):
            return NotImplemented
        return self.numerator * other.denominator == other.numerator * self.denominator
  3. Fraction(1, 2) == Fraction(2, 4) is True because 1·4 = 2·2. Returning NotImplemented for 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

  1. In f1 + f2, Python first invokes f1.__add__(f2). Thus self is f1 and other is f2.

  2. 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

  1. __add__ should return a new Fraction instance holding the sum’s numerator and denominator.

  2. 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)).numerator is 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

  1. f1 + f2 calls __add__ and, in this class, returns a new Fraction value. Its string form is used only when the result is printed.

  2. f1 == f2 calls __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).