import statistics
class Student:
"""Student class definition"""
def __init__(self, name: str):
"""Student class constructor"""
self.name = name # Student class properties
self.grades = []
# Student class methods
def take_class(self, grade: float):
self.grades.append(grade)
def gpa(self) -> float:
return statistics.mean(self.grades)Lab 07
Classes
1 Today
- Classes
- In class exercise
2 Recap: Classes
What are classes? What are some important elements to remember when making a class?
Recall this class we introduced a couple of week ago:
romi = Student("Romi")print(romi.name)
print(romi.grades)Romi
[]
romi.take_class(3.5)print(romi.grades)[3.5]
2.1 Discussion
Say I want make a class on information that a song may contain. How would I make a class
Song(), that contains the name of the song, the artist of the song, the genres of the song, and the year it was released?For example, make a variable
down_underwhich has the following information: - Name:"Down Under"- Artist:"Men at Work"- Genre:["Pop", "Rock"]- Year:1981
Expected output:
down_under = Song("Down Under", "Men at Work", ["Pop", "Rock"], 1981)down_under.name'Down Under'
down_under.artist'Men at Work'
down_under.genre['Pop', 'Rock']
down_under.year1981
How do I add a new method to the Class, which adds a new genre to it?
For example:
down_under = Song("Down Under", "Men at Work", ["Pop", "Rock"], 1981)
down_under.add_genre("Classic Rock")
down_under.genre['Pop', 'Rock', 'Classic Rock']
3 In Class Exericses
Make a class Cat which contains a cat’s name, color, and its average walking speed (speed, in feet/second. The average walking pace of a cat is around 4 feet per second).
For example:
mittens = Cat("Mittens", "brown", 4)mittens.name'Mittens'
mittens.color'brown'
mittens.speed4
Add a method: Make a new method meow that takes an int and prints out that number of meows. Hint: Use a for loop.
mittens.meow(5)Meow!
Meow!
Meow!
Meow!
Meow!
Challenge! Make a method move() in your Cat class that takes a distance (int) in feet as input, and prints out how long it took for your cat to travel that distance. Recall from high school math that \(time = \frac{distance}{speed}\)
For example:
mittens.move(30)It took Mittens 7.5 seconds to travel 30 feet.