See
“Class
instantiation”
in
Class
Objects.
The
__init__
method of class has two underscores in front and two in back.
That’s because
__init__
is a
special
method.
"""
Create a class named Person. Then instantiate this class several times,
i.e., create several instantiations (objects) of this class.
"""
import sys
class Person(object): #The (object) is unnecessary: you get it anyway.
"Class Person demonstrates the __init__method and 3 instance attributes."
def __init__(self, lastName, age, favoriteSongs = None):
"If the arguments are valid, instantiate a Person object."
if not isinstance(lastName, str):
raise TypeError("lastName must be a str")
if lastName == "":
raise ValueError("lastName must not be empty")
if not isinstance(age, (int, float)):
raise TypeError("age must be int or float")
if age < 0 or age > 120:
raise ValueError("age must be in the range 0 to 120 inclusive")
if not isinstance(favoriteSongs, list) and favoriteSongs is not None:
raise TypeError("favoriteSongs must be list or None")
self.lastName = lastName
self.age = age
self.favoriteSongs = favoriteSongs
#Create one instance of class Person:
try:
mark = Person("Meretzky", 64, ["Help!", "Day Tripper", "Piggies"])
except BaseException as error:
print(error, file = sys.stderr)
sys.exit(1)
print(f'mark.lastName = "{mark.lastName}"')
print(f"mark.age = {mark.age}")
print(f"mark.favoriteSongs = {mark.favoriteSongs}")
print()
#Mass produce many instances of class Person. Store them in a list.
students = [
["Chan", 10],
["Cooper", 20],
["Franklin", 30],
["Hsu", 40],
["Leyl", 50],
["Phu", 60],
["Rutledge", 70]
]
lengths = [len(student[0]) for student in students] #Each student is a list containing 2 items.
maxLength = max(lengths)
try:
persons = [Person(*student) for student in students] #Each student is a list containing 2 items.
except BaseException as error:
print(error, file = sys.stderr)
sys.exit(1)
for person in persons:
print(f"{person.lastName:{maxLength}} {person.age:3}")
sys.exit(0)
mark.lastName = "Meretzky" mark.age = 64 mark.favoriteSongs = ['Help!', 'Day Tripper', 'Piggies'] Chan 10 Cooper 20 Franklin 30 Hsu 40 Leyl 50 Phu 60 Rutledge 70
__init__?
__init__
raise a
TypeError
if
favoriteSongs
contains an item that is not a
string.
I hope every
bool
in the following
listOfBools
is
True.
if favoriteSongs is not None:
if not isinstance(favoriteSongs, list):
raise TypeError("favoriteSongs must be list or None")
listOfBools = [isinstance(song, str) for song in favoriteSongs]
if not all(listOfBools):
raise TypeError("Every song must be a str")