Questions
Solutions for each problem can be found at the bottom of this page.
Conceptual Questions
- A class definition provides a pattern for creating objects, but doesn’t make any objects itself. (T/F)
- By convention, Python class names start with a lowercase letter. (T/F)
- When you define a method in a class, all objects of that class have that method associated with it. (T/F)
- The first parameter of a method is a copy of the object the method is called on called
self. (T/F) - A class definition must come before an object of that class is instantiated. (T/F)
- You must have an instance of a class (an object) to call the class’s constructor. (T/F)
- Constructors must have the
selfparameter in their signature. (T/F) - Constructors must take at least one parameter other than the self parameter. (T/F)
- Objects are passed into functions by reference. (T/F)
- The type of an object is the same as the name of the class it is an instance of. (T/F)
Memory Diagrams
Focus on the Recursion memory diagrams on the practice memory diagram page.
Class Writing
- This class is slightly challenging, but take it step by step! Create a
ChristmasTreeFarmclass with the following specifications:- The
ChristmasTreeFarmclass should have one attribute: alist[int]namedplots.- Basic behavior of
plots(you will define this later):- This list will hold values that represent the size of the tree planted in each plot.
- If the value at an index of the list is 0, then the plot at that index is empty (does not have a tree).
- Any value other than 0 indicates that a tree is growing in that plot!
- Basic behavior of
- The constructor for the class should take two arguments:
plots: intandinitial_planting: int, both of type int.- The first parameter,
plots, represents the total number of plots in the farm. (Notice that the attributeplotsand the parameterplotsfor this constructor are different, and represent different things!) - The second parameter,
initial_planting, represents the number of plots that that will have trees already planted in them. These initially planted plots will be trees of size 1. - The constructor should initialize the
plotsattribute to an emptylist, and then appendinitial_plantingtrees of size 1. After that, the constructor should fill the rest of the plots with zeroes to indicate that they are empty!
- The first parameter,
- The class should define a method called
plant.- This method should have a parameter of type
int, representing the plot index at which a tree should be planted. - The tree should be size 1 when planted. If this method is called on a plot that already has a tree, the old tree will be uprooted and replaced with a new baby tree (size 1).
- This method should have a parameter of type
- The class should define a method called
growth.- This method should increase the size of each planted tree by 1. (Remember that unplanted plots are represented by a 0 in the
plotslist.)
- This method should increase the size of each planted tree by 1. (Remember that unplanted plots are represented by a 0 in the
- The class should define a method called
harvest.- This method should have a parameter
replantof typeboolthat will determine whether this method replants trees (sets them to size 1 after harvest) or leaves the plots empty (sets them to size 0 after harvest). - For this method, trees that are at least size 5 will be harvested. The method will
returnthe count of how many trees were successfully harvested (typeint).
- This method should have a parameter
- The
- Write a Python class called
Carthat represents a basic model of a car with the following specifications:
- Include attributes
make: str,model: str,year: int,color: str, andmileage: float.
- Write a constructor to initialize all attributes.
- Implement a method for updating the mileage of the car,
update_mileage, that takes an amount ofmiles: floatas input and updated the mileage attribute. - Implement a method displaying the car’s attribute information as a string called
display_info. It should just print the information and not return anything. (You can take creative liberty, as long as it prints out all attributes!) - Implement a function (NOT a method) called
calculate_depreciationthat calculates the depreciation of the car by taking aCarobject as input anddepreciation_rate: floatand returns the mileage multiplied by the depreciation rate.
Practice calling these methods by instantiating a new car object and calling them!
Function Writing with Class Objects
- Write a function (NOT A METHOD) called
find_courses. Given the followingCourseclass definition,find_coursesshould take in alist[Course]and astrprerequisite to search for. The function should return a list of thenamesof each Course whoselevelis 400+ and whoseprerequisiteslist contains the given string.
class Course:
"""Models the idea of a UNC course."""
name: str
level: int
prerequisites: list[str]
- Write a method called
is_valid_coursefor theCourseclass. The method should take in astrprerequisite and return aboolthat represents whether the course’slevelis 400+ and if itsprerequisiteslist contains the given string.
Solutions
Conceptual Questions
- True
- False
- True
- False
- True
- False
- True
- False
- True
- True
Class Writing Solutions
"""Diagraming practice for Quiz 03."""
class ChristmasTreeFarm:
"""A christmas tree farm!"""
plots: list[int]
def __init__(self, plots: int, initial_planting: int) -> None:
"""Sets up the farm."""
self.plots = []
i: int = 0
while i< initial_planting:
self.plots.append(1)
i += 1
while i < plots:
self.plots.append(0)
i += 1
def plant(self, plot_number: int) -> None:
"""Plants a tree at the given plot number."""
self.plots[plot_number] = 1
def growth(self) -> None:
"""Grows each planted tree."""
i: int = 0
while i < len(self.plots):
if self.plots[i] != 0:
self.plots[i] += 1
i += 1
def harvest(self, replant: bool) -> int:
"""Harvest trees that are fully grown!"""
total: int = 0
i: int = 0
while i < len(self.plots):
if self.plots[i] >= 5:
total += 1
if replant:
self.plots[i] = 1
else:
self.plots[i] = 0
i += 1
return total
class Car:
make: str
model: str
year: int
color: str
mileage: float
def __init__(self, make: str, model: str, year: int, color: str, mileage: float):
self.make = make
self.model = model
self.year = year
self.color = color
self.mileage = mileage
def update_mileage(self, miles: float) -> None:
self.mileage += miles
def display_info(self) -> None:
info: str = f"This car is a {self.color}, {self. year} {self.make} {self.model} with {self.mileage} miles."
print(info)
def calculate_depreciation(vehicle: Car, depreciation_rate: float) -> float:
return vehicle.mileage * depreciation_rate
to practice instantiating:
my_ride: Car = Car("Honda", "CRV", "2015", "blue", 75000.00)
my_ride.update_mileage(5000.25)
my_ride.display_info()
calculate_depreciation(my_ride, .01)
Function Writing
def find_courses(courses: list[Course], prereq: str) -> list[str]:
"""Finds 400+ level courses with the given prereq."""
results: list[str] = []
for c in courses:
if c.level >= 400:
for p in c.prerequisites:
if p == prereq:
results.append(c.name)
return results
def is_valid_course(self, prereq: str) -> bool:
"""Checks if this course is 400+ level and has the given prereq."""
if self.level < 400:
return False
else:
for p in self.prerequisites:
if p == prereq:
return True
return False