Programming Foundations with Python
Objects, invariants and recursion
Objects that own a state invariant
A class defines a type; calling it creates an instance and invokes its initialization method. An instance attribute belongs to that particular object. A method combines a function with an instance: `a.book(20)` supplies `a` as the first argument named `self`. That name is a convention rather than a special keyword. Two names can refer to one instance, so changing the object through one name is visible through the other. Creating two instances instead gives two separate sets of instance attributes.
Use a class when an operation must maintain related state through several calls. Pure functions remain a good choice for independent calculations. Consider a synthetic nonnegative work budget, with integer minutes and no refunds. The invariant is `0 <= used <= limit`. Initialization establishes it, and each successful booking must preserve it. Reject a proposed booking before changing state; a failed booking must leave the object unchanged.
class WorkBudget:
def __init__(self, limit):
if type(limit) is not int:
raise TypeError('integer minutes excluding bool required')
if limit < 0:
raise ValueError('nonnegative limit required')
self._limit = limit
self._used = 0
@property
def remaining(self):
return self._limit - self._used
def book(self, minutes):
if type(minutes) is not int:
raise TypeError('integer minutes excluding bool required')
if minutes < 0 or minutes > self.remaining:
raise ValueError('booking exceeds the remaining budget')
self._used += minutes
return self.remainingFor `a=WorkBudget(60)`, the state starts at used 0 and remaining 60. Booking 35 yields used 35 and remaining 25. Booking another 30 raises before assignment, so remaining stays 25. Booking zero succeeds without changing the invariant. Negative minutes are rejected rather than interpreted as cancellation; cancellation would require its own stated policy. The arithmetic proof is local: an accepted amount is between zero and `limit-used`, so the new used value is at least zero and at most limit.
The leading underscore signals an implementation detail. It does not enforce authorization or prevent a caller from writing `a._used=1000`. The invariant is guaranteed by the supplied interface under its assumptions, not against arbitrary modification of the object. A read-only property makes the supported observation convenient; it does not turn Python objects into security boundaries. The HTTP and database layers retain their separate validation and tenant checks.
Never put per-instance mutable state in a shared class attribute by accident. If a class body contains `visits=[]`, ordinary attribute lookup can find that same list through every instance, and `self.visits.append(...)` changes the shared object. Assign `self.visits=[]` inside initialization when each instance should own its list. This is the class version of the earlier mutable-default and shallow-copy problem. A class attribute is appropriate for deliberately shared constants, provided their mutation policy is understood.
Inheritance lets a derived class reuse and override behavior. A derived `TrainingBudget(WorkBudget)` inherits `book` and `remaining`; it can add a label without duplicating the booking rule. If it overrides initialization, `super().__init__(limit)` establishes the base invariant before it adds its own state. An override of `book` that silently permits overbooking breaks the promise a caller expects from a WorkBudget. Reuse alone is not a justification for inheritance: composition, such as a scheduler holding a WorkBudget instance, often expresses the relationship more clearly. Methods are selected using the actual object's type, so an override affects calls made through a variable referring to that derived instance.
Recursion: a smaller problem and a suspended caller
A recursive function invokes itself on a smaller problem. Correctness needs a base case, a justified relationship between the smaller answer and the requested answer, and a decreasing measure that reaches the base case on the accepted domain. Separate calls have separate local bindings. While a child call runs, its caller can remain suspended with work still to do.
def triangular(n):
if type(n) is not int:
raise TypeError('built-in integer excluding bool required')
if not 0 <= n <= 100:
raise ValueError('teaching domain is 0 through 100')
if n == 0:
return 0
return n + triangular(n - 1)The requested result is the sum of integers 1 through n. At n=0 the empty sum is zero. Assuming the smaller call returns the sum through n-1, adding n gives the sum through n. The nonnegative integer n decreases by one on every recursive call, proving mathematical termination in this finite domain. Domain validation matters: allowing negative input with only the zero base case would keep moving away from zero.
For n=3 the calls descend as 3, 2, 1, 0. The frame for n=3 waits to add 3; the frame for n=2 waits to add 2; the frame for n=1 waits to add 1. The returns unwind as 0, 1, 3, 6. Returning zero at every call would terminate but fail the result contract. Printing the intermediate values is also different from returning a value that the suspended caller can use.
This implementation uses a number of calls and retained frames proportional to n; the additions also operate on integers whose bit lengths grow. Python imposes a recursion limit, and mathematical termination does not guarantee that a particular runtime has enough stack space. The small domain is an educational bound, not a proof about the stack state of every caller. Do not raise the interpreter's recursion limit as a substitute for designing an iterative traversal. An iterative equivalent starts `total=0` and adds each value in `range(1,n+1)`, retaining a fixed number of integer variables. Both should be checked against the independent formula `n*(n+1)//2`.
Recursive structure is especially useful for nested input. A tree visitor handles a leaf directly and combines results from each child subtree. The decreasing measure can be the number of nodes remaining in a finite acyclic tree. A cyclic object graph violates that premise: following a parent reference indefinitely is not a smaller-tree computation. Choose an explicit visited-identity policy or an iterative work stack when graphs and depth bounds replace the tree contract. Counting nodes, counting paths, and counting distinct reachable objects are different questions.
Optional changed-record practice and complete reasoning
Start with two separate 60-minute budgets, a and b, and an alias `same=a`. Book 35 through a and 20 through same. Predict both remaining values; then attempt a 10-minute booking through a and inspect the state after failure. Compare this with a class-level shared visits list. Finally trace triangular(4), identify its deepest base case and independently verify the result. Change the input to -1 and explain why validation belongs before recursion.
Compare the complete changed-record reasoning
The two successful calls affect the same a object, so a and same both show 5 remaining. The separate b still has 60. The 10-minute request exceeds 5 and raises before mutation, leaving 5. A shared class-level visits list would instead be one list observable through both instances unless each instance creates its own list. For triangular(4), descent is 4,3,2,1,0 and returns are 0,1,3,6,10. The formula gives 4*5//2=10. Input -1 is rejected; it is not assigned an empty-sum answer. A changed base case or graph policy changes the specification and must be argued again.
Assess an optional response on four equally weighted criteria: correct state/alias trace; a preservation argument including failed operations; a complete call-and-return trace with base case and decreasing measure; and a justified choice of iteration or recursion that states resource and graph assumptions. Full credit requires mechanisms and changed facts, not only the final numbers.
Optional references: Python 3.12 tutorial, Classes; Python 3.12 sys recursion-limit documentation. The original on-site explanation above supplies the required introductory teaching; the retained publisher/reference chapters provide further examples. No turtle GUI or observed learner competency is claimed.
Optional Python3.12 class reference ยท Optional recursion-limit reference