Reputation: 95
Please help! I am unable to pass a list of parameters to create the appropriate class. The read_package () function accepts the training code and a list of its parameters as input. The body of the function should contain a dictionary that maps the workout codes and the classes that need to be called for each workout type. The function must determine the type of training and create an object of the corresponding class, passing the parameters received in the second argument to it. The function should return this object.
packages = [
('SWM', [720, 1, 80, 25, 40]),
('RUN', [15000, 1, 75]),
('WLK', [9000, 1, 75, 180]),
]
def read_package(workout_type: str, data: list):
dict = {
'SWM': Swimming(data),
'RUN': Running(data),
'WLK': Walking(data)
}
for x, y in dict.items():
if x == workout_type:
return print(y)
else:
None
for workout_type, data in packages:
training = read_package(workout_type, data)
If I understand correctly, then all three list with parameters are transferred in turn to each class. How can you fix that each list is passed to the correct class?
File "c:\Dev\task.py", line 133, in read_package
'SWM': Swimming(),
TypeError: __init__() missing 5 required positional arguments
Upvotes: 0
Views: 1453
Reputation: 4449
Your dict
is trying to create an instance of each class type with the same parameters. Since each class takes different arguments this fails. Instead, make your lookup dictionary (dict
is a bad name) contain the class instead of an instance of a class. Then you can instantiate the correct class by expanding data
using the *
operator.
def read_package(workout_type: str, data: list):
WORKOUT_CLASS_MAP = {
'SWM': Swimming,
'RUN': Running,
'WLK': Walking
}
return WORKOUT_CLASS_MAP[workout_type](*data)
Also, return print(...)
is nonsensical. I assumed you want to return the actual object you created.
Upvotes: 3