Classes and Inheritance
Algorithms, Programming, and Data Representation · Module 92313 · Chapter 11
Keep an object’s data behind a stable interface, extend a class through inheritance, and trace which implementation Python finds first. Then use shared class state to give Rabbit objects IDs and meaningful operators.
Start from memory
Answer before reading.
- Why call
get_age()instead of readingagedirectly? - Where does Python search for an inherited method?
- What does a subclass do when it needs to initialise its own state and its parent’s?
- How can a class variable provide unique IDs?
- Why can comparing Rabbit parents with
==recurse?
Check your answers
- The class can change its internal attribute name without changing callers. §11.2
- In the current class first, then upward through its superclass chain. §11.4
- Call the parent initialiser, then assign the subclass’s own attributes. §11.5
- Read the shared counter, store that value on the instance, then increment the class counter. §11.6
- Rabbit equality may compare the parents again until it reaches
None. §11.7
How to use this guide
When tracing a call, write the instance type, the search order, and the first class that defines the method.
- Day 0: §11.1–11.3; practice 1, 2, 3, 11, 14.
- Day 1: §11.4–11.5; practice 4, 5, 8, 9, 15, 16.
- Day 3: §11.6–11.7; practice 6, 7, 10, 12, 13, 17, 18.
- About day 7: Rebuild the inheritance and Rabbit derivations; solve 19–20.
- About day 14: Work both exam problems without notes.
- Before the exam: Tick only skills you can demonstrate from memory.
When stuck: draw the class chain and mark the first definition Python finds.
How the chapter fits together
Accessors separate callers from representation. Inheritance reuses and extends behaviour; method lookup chooses the nearest definition. A class variable shares a counter, while special methods connect the class to Python operators.
Encapsulate
Getter/setter §11.2
caller → method → attributeRests on: a stable public interface.
Default value §11.3
missing argument → defaultRests on: a defined method signature.
Extend
Inheritance §11.4
subclass → superclassRests on: reusable class behaviour.
Override §11.5
first matching method winsRests on: ordered method lookup.
Specialise
Class variable §11.6
shared counter → per-object IDRests on: class-wide shared state.
Custom operators §11.7
+ → __add__; == → __eq__Rests on: a deliberate meaning for syntax.
11.1 Classes and object roles
In plain words: a class describes a kind of object; each instance has its own values and uses the class’s behaviour.
data attributes = what an object is; methods = what it doesRead it as: “attributes describe the object; methods define its operations”.Data and behaviour belong together in one reusable type.When implementing a type, decide what data represents it and what operations form its interface. When using the type, create instances and call those operations. A class groups related methods in one namespace, supports modular testing, and makes behaviour reusable.
Trap: A class definition describes instances; it is not itself a particular animal.
Near miss: Two variables can refer to one instance; constructing two objects is what gives them independent state.
Recall · §11.1
- What is the class author responsible for deciding?
- What differs between instances of the same class?
Answers
- The representation and the methods that define how the object is used. §11.1
- Their instance-attribute values; their class is shared. §11.1
11.2 Getters and information hiding
In plain words: a getter reads data and a setter changes it through the class’s interface.
outside code → get_age() / set_age(value) → stored attributeRead it as: “call a method to read or update the hidden field”.Callers need not know the field’s name.If Animal renames age to years, get_age() can still return self.years while callers keep using the same method. This reduces coupling and helps maintenance. Python does not enforce privacy: direct attribute reads, writes, and new attributes are possible, so using getters and setters is a design convention rather than a security boundary.
Worked example · rename safely
- Initially store age in
self.age; implementget_ageto return it. - Later store the same value in
self.years. - Change the getter’s body only; existing callers still call
a.get_age().
Compare direct access and getters
Trap: A setter does not hide data if callers still reach in and change the attribute directly.
Near miss: a.age = "infinite" is legal Python but breaks the intended numeric meaning; validate through a setter if the class requires that rule.
Recall · §11.2
- How can a getter allow an attribute rename?
- Do getters make a Python attribute private?
Answers
- Keep its public method name and update its implementation to read the new field. §11.2
- No. They provide a stable interface by convention; direct access remains possible. §11.2
11.3 Defaults and Animal methods
In plain words: a default argument supplies a value when a caller leaves that parameter out.
def set_name(self, newname="")Read it as: “if newname is omitted, use the empty string”.An explicitly supplied argument replaces the default.An Animal can initialise age and set name to None, then provide get_age, get_name, set_age, and set_name. With set_name(newname=""), calling a.set_name() stores an empty string; calling a.set_name("Fluffy") stores the provided name.
Worked example · default versus supplied value
- Create
a = Animal(3); its name starts asNone. - Call
a.set_name(); the default stores"". - On another instance, call
set_name("Fluffy"); the supplied value is stored. - Use
get_name()to read either result.
Trace Animal defaults and accessors
Trap: A default is used only when the argument is omitted; an explicit value wins.
Near miss: Leaving a parameter out of the method call is only valid when its signature provides a default.
Recall · §11.3
- What value does
set_name()store with the shown default? - How can a caller provide a different name?
Answers
- The empty string. §11.3
- Pass it, for example
set_name("Fluffy"). §11.3
11.4 Inheritance and method lookup
In plain words: a subclass reuses a superclass’s attributes and methods, and can add more.
search current class → superclass → next ancestorRead it as: “use the first definition found while moving up the class chain”.A subclass-only method is unavailable on a plain superclass instance.Cat, Rabbit, and Dog can each extend Animal. A Cat may add speak(); a plain Animal does not gain that Cat-only method. When a Dog inherits get_age(), Python finds it in Animal if Dog does not define its own version.
Trap: Inheriting a method does not copy its definition into the subclass’s source; lookup finds it through the hierarchy.
Near miss: Calling animal.speak() is not valid merely because Cat defines speak; the object’s class must provide that method.
Recall · §11.4
- Where does lookup start?
- Does an Animal instance acquire Cat-only methods?
Answers
- In the instance’s class, then its superclass chain. §11.4
- No; Cat’s added behaviour belongs to Cat instances and its subclasses. §11.4
11.5 Extending and overriding
In plain words: a subclass can add state, extend behaviour, or override a method with its own version.
same method name in subclass → subclass version runsRead it as: “the closest matching definition wins”.If it is absent, lookup continues upward.Dog can initialise its own name and age by calling Animal.__init__(self, age), then add a friends list. It can add add_friend and age_diff, and override __str__ to print a dog-specific prefix. Shepherd can inherit from Dog, call Dog’s initialiser, add a skill, and override speak and __str__. In a single-inheritance chain, the first definition found supplies the behaviour.
Worked example · Dog initialisation
- Call
Dog("Rex", 4). - Dog passes age 4 to the Animal initialiser, which stores age and initialises name.
- Dog sets the supplied name through
set_nameand creates its own friends list. - A Dog’s
__str__is found before Animal’s; inherited getters still resolve to Animal.
This lecture uses an explicit parent call. Python also provides super(), which follows the method resolution order and is less tied to a named parent class; that is a modern extension to the lecture’s example.
Trace constructor calls and overrides
Trap: If a subclass defines __init__, it must call the parent initialiser itself when parent state is still needed.
Near miss: Defining Dog’s __str__ replaces the Animal version for Dogs; it does not automatically append the parent’s text.
Recall · §11.5
- What should Dog do before adding its own state?
- Which string method runs for a Shepherd?
Answers
- Call the parent initialiser to establish inherited state. §11.5
- The nearest definition: Shepherd’s if present, otherwise Dog’s, then Animal’s. §11.5
11.6 Class variables and IDs
In plain words: a class variable is shared by instances that use the class.
self.rid = Rabbit.tag; Rabbit.tag = Rabbit.tag + 1Read it as: “copy the shared next number to this rabbit, then advance the shared counter”.Initialise Rabbit.tag once in the class.Rabbit can start with class variable tag = 1. Each new instance stores the current tag in its own rid, then increments Rabbit.tag. The next instance receives the next number. A getter can format the ID with leading zeros, such as 001.
Worked example · unique IDs
- Initially
Rabbit.tagis 1. - The first Rabbit stores
rid = 1, then the class counter becomes 2. - The next stores
rid = 2, then the counter becomes 3. - The earlier instance keeps its own
ridwhile the shared counter advances.
Trap: Store each ID on the instance; do not use the changing class counter as though it were that rabbit’s ID.
Near miss: Incrementing self.tag can create an instance attribute and leave the shared class counter unchanged; update Rabbit.tag.
Recall · §11.6
- Which value is shared, and which belongs to one Rabbit?
- Why save an instance ID before incrementing the counter?
Answers
Rabbit.tagis shared;self.ridbelongs to one object. §11.6- So the instance keeps its assigned unique number as the shared counter moves on. §11.6
11.7 Operators and Rabbit equality
In plain words: special methods let a class give familiar syntax a meaning that fits its objects.
r1 + r2 → __add__; r1 == r2 → __eq__Read it as: “addition calls __add__; equality calls __eq__”.Choose an explicit rule for each operation.Rabbit addition can create a new Rabbit of age 0 whose parents are the two operands. Equality can mean “the same two parents”, regardless of parent order. Compare unique parent IDs rather than invoking Rabbit equality recursively on the parent objects.
Worked example · unordered parent pair
- Rabbit A has parents with IDs 4 and 9; Rabbit B has the same IDs in reverse order.
- The ordered test fails because 4 ≠ 9 in the first position.
- The reversed test succeeds: A’s first parent matches B’s second, and vice versa.
- The rabbits compare equal under the stated parent-pair rule.
There is an edge case in the lecture’s example: parent fields default to None. A safe equality method must handle None before reading .rid; otherwise comparing root rabbits raises AttributeError. Define whether two absent parents count as matching, then compare real parents by ID.
Predict Rabbit addition and equality
Trap: An equality method that calls self.parent1 == other.parent1 may invoke Rabbit’s equality again and recurse down the family tree.
Near miss: Comparing only corresponding parent positions says reversed parent order is unequal; also check the swapped pairing.
Recall · §11.7
- What does Rabbit addition return in the lecture design?
- How does the equality rule treat parent order?
Answers
- A new age-0 Rabbit whose parent fields reference the two operands. §11.7
- It accepts either the same order or the reversed order. §11.7
Decision map
| Need | Use |
|---|---|
| Keep callers stable while fields change | Getter and setter methods |
| Supply an omitted argument | A default parameter |
| Reuse and extend behaviour | Subclassing |
| Find a method implementation | Search class, then ancestors |
| Track a shared sequence of IDs | Class variable plus instance ID |
| Define object operators | __add__, __eq__ and a clear contract |
Derive it cold
- Trace
get_age()after the internal field changes from age to years. §11.2 - Follow method lookup for Shepherd → Dog → Animal. §11.4
- Trace Dog’s parent and child initialisation. §11.5
- Generate the first three Rabbit IDs from
tag = 1. §11.6 - Derive Rabbit equality for equal, reversed, and missing parents. §11.7
Explain it
- Why keep the getter name stable when representation changes?
- Why is Python’s getter/setter style not strict privacy?
- When does a default argument apply?
- Why does a subclass inherit a constructor if it defines none?
- Why does an override in Shepherd win over Dog’s version?
- Why store an ID on each Rabbit?
- Why compare parent IDs instead of parent objects?
Model answers
- Callers depend on a stable interface, not the internal field name. §11.2
- Callers can still directly read, change, or add attributes. §11.2
- When that argument is omitted from the call. §11.3
- Lookup proceeds to the superclass when the subclass has no method with that name. §11.4
- Lookup starts in Shepherd and stops at the first matching definition. §11.4
- The class counter changes; the instance needs to keep its assigned number. §11.6
- Direct equality may recursively invoke Rabbit’s method and fail at a missing parent. §11.7
Mixed practice
20 problems. Try each before opening its worked answer.
- What are data attributes and methods intended to describe?
- Why prefer
a.get_age()toa.age? - With
set_name(self, newname=""), what doesa.set_name()store? - Where does method lookup begin for a Shepherd instance?
- What should Dog call before setting its own name and friends list?
- Which object shares
Rabbit.tag? - Which method defines
r1 + r2? - If Dog has no
get_age, where is it found? - Which
__str__runs on a Shepherd if Shepherd overrides it? - Which method defines
r1 == r2? - How can Animal rename its field without changing callers?
- Tags start at 1. Which IDs do the first three rabbits receive?
- What can go wrong comparing two root rabbits by parent
.rid? - What happens if a caller passes
"Fluffy"toset_name? - Can an Animal instance call Cat’s new
speakmethod? - Why call the parent constructor in Dog?
- After the first rabbit stores ID 1, what is the next class tag?
- How should equality handle parents in reversed order?
- Do getters prevent external writes to
a.age? - Why group related methods in a class?
Show worked answers
- Attributes describe what an object is; methods describe what it does. §11.1
- The class can change its representation while keeping callers stable. §11.2
- The empty string. §11.3
- In Shepherd, then Dog, then Animal. §11.4
- Call
Animal.__init__(self, age)to initialise inherited state. §11.5 - The Rabbit class and its instances. §11.6
__add__. §11.7- In Animal, where the inherited method is defined. §11.4
- Shepherd’s override. §11.5
__eq__. §11.7- Keep
get_age()as the public interface and change its body to read the renamed field. §11.2 - 1, 2, and 3; the shared tag increments after each assignment. §11.6
None.ridraises AttributeError; handle missing parents before reading IDs. §11.7- The supplied name is stored instead of the default. §11.3
- No. That method belongs to Cat and subclasses of Cat. §11.4
- So Animal’s age and name state is initialised. §11.5
- 2. §11.6
- Check both the same-order pairing and the swapped pairing. §11.7
- No; direct attribute access remains possible in Python. §11.2
- They keep related behaviour together, aiding modularity and reuse. §11.1
Exam-style problems
Allow about 20 minutes per problem.
Problem 1 · Animal hierarchy
Animal defines age accessors and __str__. Dog inherits Animal, initialises a friends list, and overrides __str__. Shepherd inherits Dog, adds skill, and overrides speak.
- Trace which initialisers run when creating a Shepherd.
- Give the method lookup order for
get_ageand__str__. - Can an Animal object call Shepherd’s
speak? Explain. - Why use
get_age()when Animal renames its field?
Show worked answer
- Shepherd initialisation calls Dog’s initialiser, which calls Animal’s; each then stores its own fields. §11.5
get_ageis found in Animal.__str__is found in Shepherd if overridden there, otherwise Dog, then Animal. §11.4, §11.5- No. Lookup on an Animal instance searches Animal and its ancestors; it does not search subclasses. §11.4
- The getter keeps callers independent of the internal field name. §11.2
Problem 2 · Rabbit family operators
Rabbit stores a class counter, an instance ID, and two optional parent references. Define what addition and equality should mean, including edge cases.
- Trace IDs for three newly constructed Rabbits when the tag starts at 1.
- Describe the result of
r1 + r2. - State a symmetric same-parent equality rule.
- Handle root rabbits whose parent fields are
None.
Show worked answer
- They receive IDs 1, 2, and 3; the shared counter advances after each. §11.6
__add__returns a new age-0 Rabbit with r1 and r2 as its parents. §11.7- Match both IDs in the same order or both in the reversed order. §11.7
- Compare absent values explicitly (for example, None with None) before reading IDs; compare two real parent objects by their unique IDs. §11.7
Slips in the notes
- Slides 6–7, 13 and 19 show malformed constructor spellings or calls (for example,
def_init_andAnimal._init_). Valid Python usesdef __init__andAnimal.__init__. - Slides 7, 13, 14 and 17 miss or misplace underscores around the string hook (for example,
def_str__ordef str). The special method isdef __str__(self):. - Slide 21’s code label is rendered as
def_eq_, which is not a Python method definition. The intended special method isdef __eq__(self, other):; the slide’s accompanying text refers to__eq__. - The Rabbit equality example dereferences each parent’s
rid, although both parent parameters default toNone. Comparing root rabbits would therefore raiseAttributeError. This guide calls out the required missing-parent case.
Self-check
Based on the supplied “11_Classes and Inheritance.pdf”, rewritten in my own words. Python inheritance and method lookup follow the Python classes tutorial; special method names follow the data model. super() follows the built-in reference. Not an official FAU publication; check course details against current notes. Made by Thanate Amornjiraporn (Focus).