9.4.3. Homework#
Use this assignment to practice the chapter’s concepts and coding skills in runnable Python code.
Sign in from the account menu before you start working on the assignment.
Write and run your code directly in the coding cells.
Multiple submissions are allowed. The highest score is kept.
1. Class design
A support team tracks an owner and status for each ticket and provides the same close operation for every ticket. Defining a Ticket class is a suitable way to keep that state and behavior together.
2. Instance state
An Account initializer stores a numeric balance on self. Changing that balance on one account must also change the numeric balance stored on every other Account instance.
3. Bound methods
Ana stores account.deposit in a variable named action. Calling action(50) later uses that same account as the method receiver.
4. Encapsulation
A service exposes a read-only balance property and validates withdrawals before changing _balance. Callers can use the public withdrawal method without knowing how the balance is stored.
5. Inheritance decisions
A report exporter and a bank account both have an owner attribute. That shared name alone is enough reason to make the exporter inherit from the account.
### 6. Share a class-level limit
# Define Ticket with a class variable max_priority = 3 shared by all tickets.
# Add a static method is_valid_priority(priority) that returns True when
# priority is from 1 to Ticket.max_priority.
# __init__(self, owner, priority) raises ValueError("Invalid priority") unless
# Ticket.is_valid_priority(priority) is True, then stores owner and priority.
# Create a = Ticket("Ana", 2) and b = Ticket("Ben", 3), and print both tickets'
# max_priority. Set Ticket.max_priority = 5 and print both again, then print
# whether priority 4 is now valid. Assign a.max_priority = 1 and print a's,
# b's, and the class's max_priority. Finally, try Ticket("Cy", 9) and print
# "Invalid priority" when it raises ValueError. Expected output:
# Max priority: 3 3
# After change: 5 5
# Priority 4 valid: True
# Shadowed: 1 5 5
# Invalid priority
### Your code starts here.
### Your code ends here.
### 7. Combine inventory without changing the inputs
# Define StockCount(item, quantity) storing both attributes in __init__.
# Assume quantities are nonnegative integers. Implement __add__ so that two
# StockCount objects for the same item produce a new StockCount with the
# summed quantity. Return NotImplemented for a different operand type;
# raise ValueError for different item names. Leave both inputs unchanged.
# Create left = StockCount("apple", 4) and right = StockCount("apple", 6).
# Print the combined item/quantity, then both original quantities:
# Combined: apple 10
# Original quantities: 4 6
### Your code starts here.
### Your code ends here.
### 8. Implement an abstract report interface
# Use ABC and abstractmethod from abc to define Report with an abstract
# render(self) method. Define CountReport(Report) with __init__(self, counts)
# storing a dictionary of item counts and render() returning a string of
# "item=count" pairs joined by ", ", sorted alphabetically by item.
# An empty dictionary renders as an empty string. Do not print inside render.
# Write show_report(report) to print report.render(), using only that interface.
# Call show_report(CountReport({"pear": 2, "apple": 3})). Expected output:
# apple=3, pear=2
### Your code starts here.
### Your code ends here.
### 9. Call one method on different classes
# The base class Account is given below. Its month_end() leaves the balance unchanged.
# Define two subclasses of Account that override month_end():
# - CheckingAccount: subtracts a 10.0 monthly service fee from self.balance
# - SavingsAccount: adds monthly interest of self.balance * 0.02
# Create this list:
# accounts = [CheckingAccount("Ana", 500.0), SavingsAccount("Ben", 1000.0), Account("Cy", 300.0)]
# Write one loop that calls account.month_end() on every account (no if/elif on the
# account type) and then prints the owner and balance with 2 decimal places.
# Print exactly these three lines:
# Ana: 490.00
# Ben: 1020.00
# Cy: 300.00
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def month_end(self):
pass # a basic account has no monthly change
### Your code starts here.
### Your code ends here.
### 10. Define a dataclass
# Import dataclass from the dataclasses module. Define Transaction with
# @dataclass(order=True) and these fields in this order:
# amount: float, account: str, category: str with default "general"
# Do not write __init__, __repr__, __eq__, or __lt__ yourself; let @dataclass generate them.
# Create t1 = Transaction(42.5, "A-1", "groceries"), t2 = Transaction(12.0, "A-2"),
# and t3 = Transaction(42.5, "A-1", "groceries").
# Print t2, then print whether t1 == t3, then print the amounts of sorted([t1, t2, t3]).
# Print exactly these three lines:
# Transaction(amount=12.0, account='A-2', category='general')
# Equal: True
# Sorted amounts: [12.0, 42.5, 42.5]
### Your code starts here.
### Your code ends here.