APDR

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.

  1. Why call get_age() instead of reading age directly?
  2. Where does Python search for an inherited method?
  3. What does a subclass do when it needs to initialise its own state and its parent’s?
  4. How can a class variable provide unique IDs?
  5. Why can comparing Rabbit parents with == recurse?
Check your answers
  1. The class can change its internal attribute name without changing callers. §11.2
  2. In the current class first, then upward through its superclass chain. §11.4
  3. Call the parent initialiser, then assign the subclass’s own attributes. §11.5
  4. Read the shared counter, store that value on the instance, then increment the class counter. §11.6
  5. 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.

  1. Day 0: §11.1–11.3; practice 1, 2, 3, 11, 14.
  2. Day 1: §11.4–11.5; practice 4, 5, 8, 9, 15, 16.
  3. Day 3: §11.6–11.7; practice 6, 7, 10, 12, 13, 17, 18.
  4. About day 7: Rebuild the inheritance and Rabbit derivations; solve 19–20.
  5. About day 14: Work both exam problems without notes.
  6. 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 → attribute

    Rests on: a stable public interface.

  • Default value §11.3

    missing argument → default

    Rests on: a defined method signature.

Extend

  • Inheritance §11.4

    subclass → superclass

    Rests on: reusable class behaviour.

  • Override §11.5

    first matching method wins

    Rests on: ordered method lookup.

Specialise

  • Class variable §11.6

    shared counter → per-object ID

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

Object designdata 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

  1. What is the class author responsible for deciding?
  2. What differs between instances of the same class?
Answers
  1. The representation and the methods that define how the object is used. §11.1
  2. 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.

Access through an interfaceoutside 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

  1. Initially store age in self.age; implement get_age to return it.
  2. Later store the same value in self.years.
  3. Change the getter’s body only; existing callers still call a.get_age().

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

  1. How can a getter allow an attribute rename?
  2. Do getters make a Python attribute private?
Answers
  1. Keep its public method name and update its implementation to read the new field. §11.2
  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.

Default parameterdef 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

  1. Create a = Animal(3); its name starts as None.
  2. Call a.set_name(); the default stores "".
  3. On another instance, call set_name("Fluffy"); the supplied value is stored.
  4. Use get_name() to read either result.

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

  1. What value does set_name() store with the shown default?
  2. How can a caller provide a different name?
Answers
  1. The empty string. §11.3
  2. 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.

Lookup rulesearch 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.
One branch of the animal hierarchy. The German Shepherd inherits from Dog, which inherits from Animal.

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

  1. Where does lookup start?
  2. Does an Animal instance acquire Cat-only methods?
Answers
  1. In the instance’s class, then its superclass chain. §11.4
  2. 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.

Override selectionsame 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

  1. Call Dog("Rex", 4).
  2. Dog passes age 4 to the Animal initialiser, which stores age and initialises name.
  3. Dog sets the supplied name through set_name and creates its own friends list.
  4. 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.

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

  1. What should Dog do before adding its own state?
  2. Which string method runs for a Shepherd?
Answers
  1. Call the parent initialiser to establish inherited state. §11.5
  2. 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.

Rabbit ID assignmentself.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

  1. Initially Rabbit.tag is 1.
  2. The first Rabbit stores rid = 1, then the class counter becomes 2.
  3. The next stores rid = 2, then the counter becomes 3.
  4. The earlier instance keeps its own rid while 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

  1. Which value is shared, and which belongs to one Rabbit?
  2. Why save an instance ID before incrementing the counter?
Answers
  1. Rabbit.tag is shared; self.rid belongs to one object. §11.6
  2. 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.

Rabbit operationsr1 + 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

  1. Rabbit A has parents with IDs 4 and 9; Rabbit B has the same IDs in reverse order.
  2. The ordered test fails because 4 ≠ 9 in the first position.
  3. The reversed test succeeds: A’s first parent matches B’s second, and vice versa.
  4. 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.

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

  1. What does Rabbit addition return in the lecture design?
  2. How does the equality rule treat parent order?
Answers
  1. A new age-0 Rabbit whose parent fields reference the two operands. §11.7
  2. It accepts either the same order or the reversed order. §11.7

Decision map

NeedUse
Keep callers stable while fields changeGetter and setter methods
Supply an omitted argumentA default parameter
Reuse and extend behaviourSubclassing
Find a method implementationSearch class, then ancestors
Track a shared sequence of IDsClass variable plus instance ID
Define object operators__add__, __eq__ and a clear contract

Derive it cold

  1. Trace get_age() after the internal field changes from age to years. §11.2
  2. Follow method lookup for Shepherd → Dog → Animal. §11.4
  3. Trace Dog’s parent and child initialisation. §11.5
  4. Generate the first three Rabbit IDs from tag = 1. §11.6
  5. Derive Rabbit equality for equal, reversed, and missing parents. §11.7

Explain it

  1. Why keep the getter name stable when representation changes?
  2. Why is Python’s getter/setter style not strict privacy?
  3. When does a default argument apply?
  4. Why does a subclass inherit a constructor if it defines none?
  5. Why does an override in Shepherd win over Dog’s version?
  6. Why store an ID on each Rabbit?
  7. Why compare parent IDs instead of parent objects?
Model answers
  1. Callers depend on a stable interface, not the internal field name. §11.2
  2. Callers can still directly read, change, or add attributes. §11.2
  3. When that argument is omitted from the call. §11.3
  4. Lookup proceeds to the superclass when the subclass has no method with that name. §11.4
  5. Lookup starts in Shepherd and stops at the first matching definition. §11.4
  6. The class counter changes; the instance needs to keep its assigned number. §11.6
  7. 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.

  1. What are data attributes and methods intended to describe?
  2. Why prefer a.get_age() to a.age?
  3. With set_name(self, newname=""), what does a.set_name() store?
  4. Where does method lookup begin for a Shepherd instance?
  5. What should Dog call before setting its own name and friends list?
  6. Which object shares Rabbit.tag?
  7. Which method defines r1 + r2?
  8. If Dog has no get_age, where is it found?
  9. Which __str__ runs on a Shepherd if Shepherd overrides it?
  10. Which method defines r1 == r2?
  11. How can Animal rename its field without changing callers?
  12. Tags start at 1. Which IDs do the first three rabbits receive?
  13. What can go wrong comparing two root rabbits by parent .rid?
  14. What happens if a caller passes "Fluffy" to set_name?
  15. Can an Animal instance call Cat’s new speak method?
  16. Why call the parent constructor in Dog?
  17. After the first rabbit stores ID 1, what is the next class tag?
  18. How should equality handle parents in reversed order?
  19. Do getters prevent external writes to a.age?
  20. Why group related methods in a class?
Show worked answers
  1. Attributes describe what an object is; methods describe what it does. §11.1
  2. The class can change its representation while keeping callers stable. §11.2
  3. The empty string. §11.3
  4. In Shepherd, then Dog, then Animal. §11.4
  5. Call Animal.__init__(self, age) to initialise inherited state. §11.5
  6. The Rabbit class and its instances. §11.6
  7. __add__. §11.7
  8. In Animal, where the inherited method is defined. §11.4
  9. Shepherd’s override. §11.5
  10. __eq__. §11.7
  11. Keep get_age() as the public interface and change its body to read the renamed field. §11.2
  12. 1, 2, and 3; the shared tag increments after each assignment. §11.6
  13. None.rid raises AttributeError; handle missing parents before reading IDs. §11.7
  14. The supplied name is stored instead of the default. §11.3
  15. No. That method belongs to Cat and subclasses of Cat. §11.4
  16. So Animal’s age and name state is initialised. §11.5
  17. 2. §11.6
  18. Check both the same-order pairing and the swapped pairing. §11.7
  19. No; direct attribute access remains possible in Python. §11.2
  20. 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.

  1. Trace which initialisers run when creating a Shepherd.
  2. Give the method lookup order for get_age and __str__.
  3. Can an Animal object call Shepherd’s speak? Explain.
  4. Why use get_age() when Animal renames its field?
Show worked answer
  1. Shepherd initialisation calls Dog’s initialiser, which calls Animal’s; each then stores its own fields. §11.5
  2. get_age is found in Animal. __str__ is found in Shepherd if overridden there, otherwise Dog, then Animal. §11.4, §11.5
  3. No. Lookup on an Animal instance searches Animal and its ancestors; it does not search subclasses. §11.4
  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.

  1. Trace IDs for three newly constructed Rabbits when the tag starts at 1.
  2. Describe the result of r1 + r2.
  3. State a symmetric same-parent equality rule.
  4. Handle root rabbits whose parent fields are None.
Show worked answer
  1. They receive IDs 1, 2, and 3; the shared counter advances after each. §11.6
  2. __add__ returns a new age-0 Rabbit with r1 and r2 as its parents. §11.7
  3. Match both IDs in the same order or both in the reversed order. §11.7
  4. 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_ and Animal._init_). Valid Python uses def __init__ and Animal.__init__.
  • Slides 7, 13, 14 and 17 miss or misplace underscores around the string hook (for example, def_str__ or def str). The special method is def __str__(self):.
  • Slide 21’s code label is rendered as def_eq_, which is not a Python method definition. The intended special method is def __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 to None. Comparing root rabbits would therefore raise AttributeError. 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).