APDR

Object-Oriented Programming

Algorithms, Programming, and Data Representation · Module 92313 · Chapter 10

Build a type by joining a data representation to a clear interface. Practise creating instances, defining methods, and giving objects meaningful behaviour.

Start from memory

Answer before reading.

  1. What two things does an object abstraction combine?
  2. What is the difference between a class and an instance?
  3. Why does an instance method take self?
  4. What must __str__ return?
  5. How does c.distance(o) relate to the class method?
Check your answers
  1. Internal data representation and an interface of operations. §10.1
  2. A class defines a type; an instance is one object of that type. §10.2
  3. Python supplies the instance as the first argument. §10.4
  4. A string describing the object. §10.5
  5. It is equivalent to Coordinate.distance(c, o). §10.4

How to use this guide

For each example, trace which object owns each value and which method receives it.

  1. Day 0: §10.1–10.3; practice 1, 4, 7, 10, 13.
  2. Day 1: §10.4–10.5; practice 2, 5, 8, 11, 14.
  3. Day 3: §10.6–10.7; practice 3, 6, 9, 12, 15.
  4. About day 7: Rebuild the derivations and solve 16–20.
  5. About day 14: Solve both exam problems without notes.
  6. Before the exam: Tick only skills you can demonstrate from memory.

When stuck: draw the instance, its attributes, and the method call’s argument list.

How the chapter fits together

Abstraction hides representation behind an interface. Classes define the common structure; instances hold their own data. Methods operate on instances, while special methods connect a class to Python syntax.

Represent

  • Abstraction §10.1

    representation + interface

    Rests on: data and operations with a shared purpose.

  • Class §10.2

    type definition

    Rests on: a reusable object design.

Operate

  • Instance §10.3

    self.x = x

    Rests on: per-object attribute values.

  • Method §10.4

    obj.method(arg)

    Rests on: an instance and its interface.

Integrate

  • Special method §10.6

    obj + other → __add__

    Rests on: a defined meaning for an operation.

  • Fraction §10.7

    numerator / denominator

    Rests on: representation plus arithmetic interface.

10.1 Objects and abstraction

In plain words: an object keeps related data together and offers operations for using it.

Object abstractionrepresentation + interfaceThe interface defines behaviour while hiding implementation.

Every Python value is an object with a type. Its representation may be simple or composite; its interface says how other code can interact with it. A list exposes indexing and methods such as append, while its internal storage should remain hidden behind those operations. Use del to remove a name or reference; Python reclaims objects that are no longer accessible through garbage collection.

Worked example · list abstraction

  1. Need an ordered collection: choose a list object.
  2. Read an item through L[i] and add one with L.append(x).
  3. Use the interface instead of relying on how the list is stored internally.

Trap: An object’s visible behaviour does not reveal its internal representation.

Near miss: Directly changing assumed list storage nearly works, but can violate the list’s invariants; use its methods.

Recall · §10.1

  1. What parts form an object abstraction?
  2. Why hide representation?
Answers
  1. Data representation and an interaction interface. §10.1
  2. Users can rely on behaviour without depending on implementation details. §10.1

10.2 Classes and instances

In plain words: a class describes a kind of object; an instance is one object made from that description.

Class and instanceinstance = Class(arguments)The call creates one object of the class.

Define a class with class. A class can have data attributes and methods. For example, Coordinate is a class, while c = Coordinate(3, 4) creates an instance. The class is the shared design; each instance is a distinct object. Grouping data with its methods makes a unit easier to test and reuse. A subclass can later extend or redefine selected behaviour from a superclass; inheritance is developed in the next chapter.

Worked example · two coordinates

  1. c = Coordinate(3, 4) and origin = Coordinate(0, 0) create two instances.
  2. Both have the Coordinate type, but their coordinates differ.
  3. isinstance(c, Coordinate) checks membership in that type.

Trap: Defining a class does not itself create all its instances.

Near miss: Two variables assigned the same instance are aliases, not two separately constructed objects.

Recall · §10.2

  1. What does a class define?
  2. What does isinstance check?
Answers
  1. A type’s attributes and behaviour. §10.2
  2. Whether an object is an instance of a given class or compatible subclass. §10.6

10.3 Initialisation and attributes

In plain words: initialisation gives a new instance the data it needs.

Instance assignmentself.attribute = valueStores a value on this instance.

Define __init__(self, x, y) to assign instance variables such as self.x = x. Python creates the instance and passes it as self; callers supply the other arguments. Do not pass self yourself.

Worked example · initialise a coordinate

  1. Call Coordinate(3, 4).
  2. Python makes a new Coordinate instance and calls its initialiser.
  3. The initialiser stores x and y on that instance.
  4. Read them later as c.x and c.y.

Trap: __init__ initialises an already-created instance; it is not called with an explicit self.

Near miss: Assigning x = x changes only a local name; self.x = x stores an instance attribute.

Recall · §10.3

  1. What does self.x = x do?
  2. Which arguments does the caller provide?
Answers
  1. Stores the supplied value on the current instance. §10.3
  2. The arguments other than self; Python supplies the instance. §10.3

10.4 Methods and self

In plain words: a method is a function defined by a class that works with an instance.

Bound method callobj.method(arg) = Class.method(obj, arg)Python supplies the instance as the first argument.

By convention, the first parameter is named self. Dot notation calls a method on an object. Python supplies that object as the first argument. Thus c.distance(origin) is equivalent to Coordinate.distance called with c and origin.

Worked example · distance between coordinates

  1. Let c = Coordinate(3, 4) and origin = Coordinate(0, 0).
  2. The method receives self = c and other = origin.
  3. It computes (3 − 0)² + (4 − 0)² = 25, then takes the square root.
  4. The distance is 5.

Trap: The first argument is present even when it is omitted from the dot call.

Near miss: c.distance() lacks the required other coordinate; pass it as the second argument.

Recall · §10.4

  1. What does Python bind to self?
  2. Rewrite a dot method call using the class name.
Answers
  1. The instance before the dot. §10.4
  2. obj.method(arg) becomes Class.method(obj, arg). §10.4

10.5 String representations

In plain words: a custom string representation makes an object’s printed form informative.

String representation__str__(self) → strReturn the text for the object.

Without __str__, printing an instance usually gives a technical default representation. Define __str__ to return a string. Python calls it when print needs the object’s text. For a coordinate, it could return <3,4>.

Worked example · coordinate text

  1. For x=3 and y=4, build the text <3,4>.
  2. Return that string from __str__.
  3. print(c) displays the returned string.

Trap: __str__ returns a string; printing inside it is not a substitute.

Near miss: Returning the pair (x, y) is useful data but not the required string; convert it to text.

Recall · §10.5

  1. When does Python call __str__?
  2. What type must it return?
Answers
  1. When a string form is needed, including print. §10.5
  2. str. §10.5

10.6 Types and special methods

In plain words: special methods let your class define how familiar Python operations behave.

Operator methoda + b → a.__add__(b)Implement an operation only when it has a clear meaning for the type.

type(c) reports the class of an instance; isinstance(c, Coordinate) checks its class relationship. Double-underscore methods connect syntax to behaviour: __add__ for +, __sub__ for −, __eq__ for ==, __lt__ for <, and __len__ for len. Define only operations with a sensible meaning for the type.

Worked example · addition protocol

  1. Suppose a + b is meaningful for a class.
  2. Python looks for the class’s addition behaviour, commonly a.__add__(b).
  3. That method should return the defined result, not merely print it.

Trap: A special method should preserve the expected meaning of its operator.

Near miss: Defining __add__ to concatenate unrelated objects may run, but gives the operator a confusing contract; choose an operation that fits the type.

Recall · §10.6

  1. Which method supports ==?
  2. What is checked by isinstance?
Answers
  1. __eq__. §10.6
  2. Whether the object belongs to the requested class relationship. §10.6

10.7 Fraction objects

In plain words: a fraction object stores a numerator and denominator, then offers meaningful fraction operations.

Fraction representationvalue = numerator / denominatorThe denominator must be non-zero.

The lecture uses fractions as a design exercise: decide the internal representation, then define an interface such as addition, subtraction, inversion, float conversion and printing. The representation should preserve the denominator rule; arithmetic should return a fraction object or another clearly specified type.

Worked example · add two fractions

  1. Represent 1⁄2 as numerator 1 and denominator 2, and 1⁄3 as 1 and 3.
  2. Use the common denominator: 1·3 + 1·2 over 2·3.
  3. The result is 56, represented by numerator 5 and denominator 6.
  4. Check: 56 is between 12 and 1, as expected.

For a robust class, also decide how to reject a zero denominator and whether to reduce fractions. Those are design choices to state explicitly; the lecture’s slides do not specify them.

Trap: A class is not complete merely because it stores two numbers; its operations need defined behaviour.

Near miss: Inverting a fraction with zero numerator would put zero in the denominator; reject that operation or define a clear exception.

Recall · §10.7

  1. Name two data attributes for a fraction.
  2. Name two operations its interface can offer.
Answers
  1. Numerator and denominator. §10.7
  2. For example, addition and inversion, or float conversion and printing. §10.7

Decision map

NeedUse
Define a new kind of objectClass
Store values for one objectInstance attributes via self
Operate on an instanceMethod call with dot notation
Print a useful object form__str__ returning a string
Define behaviour for Python syntaxAppropriate special method
Model a fractionNumerator/denominator plus arithmetic interface

Derive it cold

  1. Trace creation of a Coordinate instance and its stored attributes. §10.3
  2. Expand a dot method call into its class method call. §10.4
  3. Build the string returned for a coordinate. §10.5
  4. Map Python operators to special methods. §10.6
  5. Derive fraction addition from numerator and denominator data. §10.7

Explain it

  1. Why keep an object’s representation behind an interface?
  2. Why distinguish a class from an instance?
  3. Why does Python pass an instance to a method?
  4. Why should __str__ return rather than print?
  5. When is a special operator method a good fit?
  6. Why should a fraction define a zero-denominator policy?
Model answers
  1. It lets the implementation change while users rely on stable behaviour. §10.1
  2. The class is the reusable type definition; each instance holds its own state. §10.2
  3. So the method can read or change that object’s attributes. §10.4
  4. Because callers such as print need the value to use as text. §10.5
  5. When the operator has a clear, conventional meaning for that type. §10.6
  6. Division by zero is undefined; callers need predictable behaviour. §10.7

Mixed practice

20 problems. Try each before opening its worked answer.

  1. List the two parts of an object abstraction.
  2. Is Coordinate a class or instance?
  3. Which method connects to +?
  4. What does self.x = x store?
  5. Who supplies self?
  6. Rewrite c.distance(o) without dot notation.
  7. What must __str__ return?
  8. Name the representation for a fraction.
  9. Why use L.append(x) rather than access list internals?
  10. What does type(c) report?
  11. For c=(3,4), what is its distance to (0,0)?
  12. If __str__ returns a tuple, what is wrong?
  13. What argument does obj.__eq__(other) receive explicitly?
  14. Which method connects to len(obj)?
  15. Compute 14 + 12.
  16. What happens to an object once del has removed the last name that refers to it?
  17. What is the inverse of 35?
  18. What policy is needed for denominator zero?
  19. Why not define every special method automatically?
  20. What does isinstance(c, Coordinate) answer?
Show worked answers
  1. Internal representation and interaction interface. §10.1
  2. A class. §10.2
  3. __add__. §10.6
  4. It assigns the parameter’s value to this instance’s x attribute. §10.3
  5. Python supplies the instance in a method call. §10.4
  6. Coordinate.distance(c, o). §10.4
  7. A string. §10.5
  8. Two integers: numerator and denominator. §10.7
  9. The interface protects implementation details and invariants. §10.1
  10. The class/type of the instance, e.g. Coordinate. §10.6
  11. 5, from √32 + 42. §10.4
  12. It must return a string, not a tuple. §10.5
  13. The other operand; self is bound by the call. §10.6
  14. __len__. §10.6
  15. 34. §10.7
  16. The garbage collector reclaims objects that can no longer be reached. §10.1
  17. 53. §10.7
  18. Reject it or define a documented error response. §10.7
  19. Only provide operations with a meaningful contract for the class. §10.6
  20. Whether c is an instance of Coordinate (or a subclass). §10.6

Exam-style problems

Allow about 20 minutes per problem.

Problem 1 · Coordinate interface

Design a Coordinate class with two values, a distance method and a printable representation.

  1. Write the initialiser signature and assignments.
  2. Trace the arguments for c.distance(origin).
  3. Calculate the distance from (3,4) to (0,0).
  4. Describe the result of print(c) with a suitable __str__.
Show worked answer
  1. def __init__(self, x, y): self.x = x; self.y = y. §10.3
  2. self is c and other is origin. §10.4
  3. √32 + 42 = 5. §10.4
  4. It displays the string returned by __str__, for example <3,4>. §10.5

Problem 2 · Fraction abstraction

Plan a Fraction class storing numerator and denominator, supporting addition, inversion and display.

  1. State its representation.
  2. Compute 12 + 13.
  3. Identify the special method for addition.
  4. Choose behaviour for a zero denominator and explain why.
Show worked answer
  1. Two integer instance attributes: numerator and denominator. §10.7
  2. 3⁄6 + 2⁄6 = 56. §10.7
  3. __add__(self, other) defines the addition behaviour. §10.6
  4. Reject construction with denominator zero (for example, raise ValueError), because the represented quotient is undefined. §10.7

Slips in the notes

  • Slides 14 and 17 omit underscores in extracted code (for example, definit and def __str__); Python syntax requires def __init__ and a colon after the definition. This guide uses valid Python syntax.
  • Slide 19’s operator names are missing their double underscores in the extracted text; the standard special-method spellings are shown in this guide.

Self-check

Based on the supplied “10_Object_Oriented_Programming.pdf”, rewritten in my own words. Python special-method behaviour follows the Python data model reference. Not an official FAU publication; check course details against current notes. Made by Thanate Amornjiraporn (Focus).