Lab 10: Classes
- Due: Friday 11/06 @ 11:59pm
- Points: 1
- Download: lab10.zip
Attendance
You need to submit the lab problems in addition to attending to get credit for lab. Students in mega lab only need to submit the lab problems. Preceptor interviews are highly recommended but not required for lab submissions.
If you are in regular lab, your TA will come around during lab to check you in. If you didn't attend for a good reason (such as being sick), fill out this form (within 2 weeks of your lab): attendance form.
Required Questions
Review
Consult the drop-downs if you need a refresher on object-oriented programming (OOP) or inheritance. It's okay to skip directly to the questions and refer back here should you get stuck.
OOP
Object-oriented programming (OOP) uses objects and classes to organize programs. Here's an example of a class:
class Car:
max_tires = 4
def __init__(self, color):
self.tires = Car.max_tires
self.color = color
def drive(self):
if self.tires < Car.max_tires:
return self.color + ' car cannot drive!'
return self.color + ' car goes vroom!'
def pop_tire(self):
if self.tires > 0:
self.tires -= 1
Class: The type of an object. The Car class describes the characteristics
of all Car objects.
Object: A single instance of a class. In Python, a new object is created by calling a class.
>>> ferrari = Car('red')
Here, ferrari is a name bound to a Car object.
Class attribute: A variable that belongs to a class and is accessed via dot
notation. The Car class has a max_tires attribute.
>>> Car.max_tires
4
Instance attribute: A variable that belongs to a particular object. Each
Car object has a tires attribute and a color attribute. Like class
attributes, instance attributes are accessed via dot notation.
>>> ferrari.color
'red'
>>> ferrari.tires
4
>>> ferrari.color = 'green'
>>> ferrari.color
'green'
Method: A function that belongs to an object and is called via dot notation.
By convention, the first parameter of a method is self.
When one of an object's methods is called, the object is implicitly provided as
the argument for self. For example, the drive method of the ferrari object
is called with empty parentheses because self is implicitly bound to the
ferrari object.
>>> ferrari = Car('red')
>>> ferrari.drive()
'red car goes vroom!'
We can also call the original Car.drive function. The original function does
not belong to any particular Car object, so we must provide an explicit
argument for self.
>>> ferrari = Car('red')
>>> Car.drive(ferrari)
'red car goes vroom!'
__init__: A special function that is called automatically when a new
instance of a class is created. To evaluate the expression Car('red'), Python
creates a new Car object, then calls the __init__ function of the Car
class with self bound to the new object and color bound to 'red'.
Inheritance
To avoid redefining attributes and methods for similar classes, we can write a
single base class from which more specialized classes inherit. For
example, we can write a class called Pet and define Dog as a subclass of
Pet:
class Pet:
def __init__(self, name, owner):
self.is_alive = True # It's alive!!!
self.name = name
self.owner = owner
def eat(self, thing):
print(self.name + " ate a " + str(thing) + "!")
def talk(self):
print(self.name)
class Dog(Pet):
def talk(self):
super().talk()
print('This Dog says woof!')
Inheritance represents a hierarchical relationship between two or more classes
where one class is a more specific version of the other: a dog is a pet.
(We use "is a" to describe this sort of relationship in OOP languages, not
to refer to the Python is operator.)
Since Dog inherits from Pet, the Dog class also inherits the Pet class's
methods, so we don't have to redefine __init__ or eat. We do want each Dog
to talk in a Dog-specific way, so we override the talk method.
We can use super() to refer to the superclass of self, and access any
superclass method as if we were an instance of the superclass. For example,
super().talk() in the Dog class calls the talk method from the Pet
class, but passes in the Dog instance as self.
Classes
Q1: WWPD: Inheritance and Class Attributes
Predict what Python will display when the following lines are entered into an
interactive session, then unlock the test to check your answers. Type FUNCTION
if you believe the answer is a function, ERROR if it errors, and NOTHING if
nothing is displayed:
python3 -m pytest -k inheritance_wwpd --unlockUnlocking Examples
>>> class A:
... x, y = 0, 0
... def __init__(self):
... return
>>> class B(A):
... def __init__(self):
... return
>>> class C(A):
... def __init__(self):
... return
>>> print(A.x, B.x, C.x)
______
>>> B.x = 2
>>> print(A.x, B.x, C.x)
______
>>> A.x += 1
>>> print(A.x, B.x, C.x)
______
>>> obj = C()
>>> obj.y = 1
>>> C.y == obj.y
______
>>> A.y = obj.y
>>> print(A.y, B.y, C.y, obj.y)
______
Remember that looking up an attribute on an instance first checks the instance's own attributes, then its class, then that class's base classes. Assigning to an attribute through an instance or a class only changes that instance or class.
Q2: Mint
A mint is a place where coins are made. In this question, you'll implement a
Mint class that can output a Coin with the correct year and worth.
- Each
Mintinstance has ayearstamp. Theupdatemethod sets theyearstamp of the instance to thepresent_yearclass attribute of theMintclass. - The
createmethod takes a subclass ofCoin(not an instance!), then creates and returns an instance of that subclass stamped with theMint's year (which may differ fromMint.present_yearif it has not been updated). - A
Coin'sworthmethod returns thecentsvalue of the coin plus one extra cent for each year of age beyond 50. A coin's age can be determined by subtracting the coin's year from thepresent_yearclass attribute of theMintclass.
class Mint:
"""A mint creates coins by stamping on years.
The update method sets the mint's stamp to Mint.present_year.
>>> mint = Mint()
>>> mint.year
2026
>>> dime = mint.create(Dime)
>>> dime.year
2026
>>> Mint.present_year = 2106 # Time passes
>>> nickel = mint.create(Nickel)
>>> nickel.year # The mint has not updated its stamp yet
2026
>>> nickel.worth() # 5 cents + (80 - 50 years)
35
>>> mint.update() # The mint's year is updated to 2106
>>> Mint.present_year = 2181 # More time passes
>>> mint.create(Dime).worth() # 10 cents + (75 - 50 years)
35
>>> Mint().create(Dime).worth() # A new mint has the current year
10
>>> dime.worth() # 10 cents + (155 - 50 years)
115
>>> Dime.cents = 20 # Upgrade all dimes!
>>> dime.worth() # 20 cents + (155 - 50 years)
125
"""
present_year = 2026
def __init__(self):
self.update()
def create(self, coin) -> 'Coin':
# Hint: coin is a class, such as Nickel or Dime, not an instance!
"*** YOUR CODE HERE ***"
def update(self) -> None:
"*** YOUR CODE HERE ***"
class Coin:
cents = None # will be provided by subclasses, but not by Coin itself
def __init__(self, year: int):
self.year = year
def worth(self) -> int:
assert self.cents is not None
"*** YOUR CODE HERE ***"
class Nickel(Coin):
cents = 5
class Dime(Coin):
cents = 10
python3 -m pytest -k MintSubmit Assignment
Submit this assignment by running Provenance: Prepare Submission Bundle from the VS Code command palette and uploading the resulting zip to Gradescope. The zip already contains the files you've edited. Lab 00 has detailed instructions.
Your responses to WWPD questions are not submitted, and they do not need to be. Lab credit is based on the code writing questions.