Homework

9.4.3. Homework#

  • Use these questions after class to check your understanding of the chapter concepts and coding skills.

  • Sign in from the account menu before you start working on the homework.

  • Complete all true/false and coding questions before you submit the homework.

  • Launch Live Code (the rocket) to write and run code in the coding cells.

  • Multiple submissions are allowed. The highest score is kept.

1. Classes

A team can define a class when several records share the same kind of data and behavior.

Hide code cell source

### Solution
# True
# A class defines the attributes and methods that every instance shares. When many records
# have the same kind of data and behavior, one class lets you create each record as an
# instance instead of repeating the structure.

2. Instances

After one Account object changes balance, every other Account instance must have the same balance.

Hide code cell source

### Solution
# False
# Each instance has its own attributes, so changing self.balance on one Account object
# does not affect any other Account. Only a class attribute is shared across instances.

3. Methods

A method is a function associated with an object and normally receives the instance as self.

Hide code cell source

### Solution
# True
# A method is a function defined inside a class. When you call account.deposit(50), Python
# passes account as the first argument, which by convention is named self.

4. Encapsulation

A class can keep related data and operations together so callers use a clearer interface.

Hide code cell source

### Solution
# True
# Encapsulation bundles data and the methods that work on it into one class. Callers use
# methods such as deposit() instead of changing internal attributes directly, which keeps
# the interface clear.

5. Inheritance

Inheritance should be used whenever two classes have any variable name in common, even if their behavior is unrelated.

Hide code cell source

### Solution
# False
# Inheritance models an is-a relationship in which a subclass shares and extends the
# behavior of its parent class. A shared variable name alone is not a reason to inherit;
# unrelated classes should stay separate.
### 6. Create and use an object
# Define a simple `Ticket` class, attach attributes, and print exactly these two lines:
# # Ticket owner: Ana
# # Ticket status: open
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
class Ticket:
    pass

ticket = Ticket()
ticket.owner = "Ana"
ticket.status = "open"
print("Ticket owner:", ticket.owner)
print("Ticket status:", ticket.status)
Ticket owner: Ana
Ticket status: open
### 7. Write an initializer
# Define `Account` with `__init__`. Print exactly this line:
# # Ana balance: 125.5
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
class Account:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

account = Account("Ana", 125.5)
print(f"{account.owner} balance:", account.balance)
Ana balance: 125.5
### 8. Add a method
# Define `Counter` with `add`. Print exactly this line:
# # Total: 8
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
class Counter:
    def __init__(self):
        self.total = 0

    def add(self, amount):
        self.total += amount

counter = Counter()
counter.add(3)
counter.add(5)
print("Total:", counter.total)
Total: 8
### 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.

Hide code cell source

### Solution
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

class CheckingAccount(Account):
    def month_end(self):
        self.balance -= 10.0   # monthly service fee

class SavingsAccount(Account):
    def month_end(self):
        self.balance += self.balance * 0.02   # monthly interest

accounts = [
    CheckingAccount("Ana", 500.0),
    SavingsAccount("Ben", 1000.0),
    Account("Cy", 300.0),
]

for account in accounts:
    account.month_end()   # polymorphic call
    print(f"{account.owner}: {account.balance:.2f}")
Ana: 490.00
Ben: 1020.00
Cy: 300.00
### 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.

Hide code cell source

### Solution
from dataclasses import dataclass

@dataclass(order=True)
class Transaction:
    amount: float
    account: str
    category: str = "general"

t1 = Transaction(42.5, "A-1", "groceries")
t2 = Transaction(12.0, "A-2")
t3 = Transaction(42.5, "A-1", "groceries")

print(t2)
print("Equal:", t1 == t3)
print("Sorted amounts:", [t.amount for t in sorted([t1, t2, t3])])
Transaction(amount=12.0, account='A-2', category='general')
Equal: True
Sorted amounts: [12.0, 42.5, 42.5]