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.
- What two things does an object abstraction combine?
- What is the difference between a class and an instance?
- Why does an instance method take
self? - What must
__str__return? - How does
c.distance(o)relate to the class method?
Check your answers
- Internal data representation and an interface of operations. §10.1
- A class defines a type; an instance is one object of that type. §10.2
- Python supplies the instance as the first argument. §10.4
- A string describing the object. §10.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.
- Day 0: §10.1–10.3; practice 1, 4, 7, 10, 13.
- Day 1: §10.4–10.5; practice 2, 5, 8, 11, 14.
- Day 3: §10.6–10.7; practice 3, 6, 9, 12, 15.
- About day 7: Rebuild the derivations and solve 16–20.
- About day 14: Solve both exam problems without notes.
- 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 + interfaceRests on: data and operations with a shared purpose.
Class §10.2
type definitionRests on: a reusable object design.
Operate
Instance §10.3
self.x = xRests 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 / denominatorRests 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.
representation + 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
- Need an ordered collection: choose a list object.
- Read an item through
L[i]and add one withL.append(x). - Use the interface instead of relying on how the list is stored internally.
Compare representation and interface
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
- What parts form an object abstraction?
- Why hide representation?
Answers
- Data representation and an interaction interface. §10.1
- 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.
instance = 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
c = Coordinate(3, 4)andorigin = Coordinate(0, 0)create two instances.- Both have the Coordinate type, but their coordinates differ.
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
- What does a class define?
- What does
isinstancecheck?
Answers
- A type’s attributes and behaviour. §10.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.
self.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
- Call
Coordinate(3, 4). - Python makes a new Coordinate instance and calls its initialiser.
- The initialiser stores
xandyon that instance. - Read them later as
c.xandc.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
- What does
self.x = xdo? - Which arguments does the caller provide?
Answers
- Stores the supplied value on the current instance. §10.3
- 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.
obj.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
- Let
c = Coordinate(3, 4)andorigin = Coordinate(0, 0). - The method receives
self = candother = origin. - It computes
(3 − 0)² + (4 − 0)² = 25, then takes the square root. - 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
- What does Python bind to
self? - Rewrite a dot method call using the class name.
Answers
- The instance before the dot. §10.4
obj.method(arg)becomesClass.method(obj, arg). §10.4
10.5 String representations
In plain words: a custom string representation makes an object’s printed form informative.
__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
- For x=3 and y=4, build the text
<3,4>. - Return that string from
__str__. 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
- When does Python call
__str__? - What type must it return?
Answers
- When a string form is needed, including
print. §10.5 str. §10.5
10.6 Types and special methods
In plain words: special methods let your class define how familiar Python operations behave.
a + 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
- Suppose
a + bis meaningful for a class. - Python looks for the class’s addition behaviour, commonly
a.__add__(b). - 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
- Which method supports
==? - What is checked by
isinstance?
Answers
__eq__. §10.6- 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.
value = 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
- Represent 1⁄2 as numerator 1 and denominator 2, and 1⁄3 as 1 and 3.
- Use the common denominator: 1·3 + 1·2 over 2·3.
- The result is 56, represented by numerator 5 and denominator 6.
- 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
- Name two data attributes for a fraction.
- Name two operations its interface can offer.
Answers
- Numerator and denominator. §10.7
- For example, addition and inversion, or float conversion and printing. §10.7
Decision map
| Need | Use |
|---|---|
| Define a new kind of object | Class |
| Store values for one object | Instance attributes via self |
| Operate on an instance | Method call with dot notation |
| Print a useful object form | __str__ returning a string |
| Define behaviour for Python syntax | Appropriate special method |
| Model a fraction | Numerator/denominator plus arithmetic interface |
Derive it cold
- Trace creation of a Coordinate instance and its stored attributes. §10.3
- Expand a dot method call into its class method call. §10.4
- Build the string returned for a coordinate. §10.5
- Map Python operators to special methods. §10.6
- Derive fraction addition from numerator and denominator data. §10.7
Explain it
- Why keep an object’s representation behind an interface?
- Why distinguish a class from an instance?
- Why does Python pass an instance to a method?
- Why should
__str__return rather than print? - When is a special operator method a good fit?
- Why should a fraction define a zero-denominator policy?
Model answers
- It lets the implementation change while users rely on stable behaviour. §10.1
- The class is the reusable type definition; each instance holds its own state. §10.2
- So the method can read or change that object’s attributes. §10.4
- Because callers such as
printneed the value to use as text. §10.5 - When the operator has a clear, conventional meaning for that type. §10.6
- Division by zero is undefined; callers need predictable behaviour. §10.7
Mixed practice
20 problems. Try each before opening its worked answer.
- List the two parts of an object abstraction.
- Is
Coordinatea class or instance? - Which method connects to
+? - What does
self.x = xstore? - Who supplies
self? - Rewrite
c.distance(o)without dot notation. - What must
__str__return? - Name the representation for a fraction.
- Why use
L.append(x)rather than access list internals? - What does
type(c)report? - For c=(3,4), what is its distance to (0,0)?
- If
__str__returns a tuple, what is wrong? - What argument does
obj.__eq__(other)receive explicitly? - Which method connects to
len(obj)? - Compute 14 + 12.
- What happens to an object once del has removed the last name that refers to it?
- What is the inverse of 35?
- What policy is needed for denominator zero?
- Why not define every special method automatically?
- What does
isinstance(c, Coordinate)answer?
Show worked answers
- Internal representation and interaction interface. §10.1
- A class. §10.2
__add__. §10.6- It assigns the parameter’s value to this instance’s x attribute. §10.3
- Python supplies the instance in a method call. §10.4
Coordinate.distance(c, o). §10.4- A string. §10.5
- Two integers: numerator and denominator. §10.7
- The interface protects implementation details and invariants. §10.1
- The class/type of the instance, e.g. Coordinate. §10.6
- 5, from √32 + 42. §10.4
- It must return a string, not a tuple. §10.5
- The other operand; self is bound by the call. §10.6
__len__. §10.6- 34. §10.7
- The garbage collector reclaims objects that can no longer be reached. §10.1
- 53. §10.7
- Reject it or define a documented error response. §10.7
- Only provide operations with a meaningful contract for the class. §10.6
- 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.
- Write the initialiser signature and assignments.
- Trace the arguments for
c.distance(origin). - Calculate the distance from (3,4) to (0,0).
- Describe the result of
print(c)with a suitable__str__.
Show worked answer
def __init__(self, x, y): self.x = x; self.y = y. §10.3selfis c andotheris origin. §10.4- √32 + 42 = 5. §10.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.
- State its representation.
- Compute 12 + 13.
- Identify the special method for addition.
- Choose behaviour for a zero denominator and explain why.
Show worked answer
- Two integer instance attributes: numerator and denominator. §10.7
- 3⁄6 + 2⁄6 = 56. §10.7
__add__(self, other)defines the addition behaviour. §10.6- 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,
definitanddef __str__); Python syntax requiresdef __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).