[Tutor] Can anyone help answer this?
Peter Otten
__peter__ at web.de
Wed Jun 10 10:31:38 EDT 2020
Alan Gauld via Tutor wrote:
> On 10/06/2020 03:29, Christine Mason wrote:
>> Given the following class definition:
>>
>> class Food:
>>
>> def __init__(self, name, taste):
>> self.name = name
>> self.taste = taste
>>
>> Write a function *createFood()* that takes a list of food items as
>> argument and creates an instance of class Food for each of them. It then
>> returns the list of instances that it has created.
>>
>> Each food item in the list that is passed as argument to *createFood()
>> *is
>> a tuple of the form ('name', 'taste'), so the list of food items might
>> look like this:
>>
>> [('curry', 'spicy'), ('pavlova', 'sweet'), ('chips', 'salty')]
>>
>> The function *createFood() *takes the two elements of each tuple and
>> passes them to the initialiser of Food. It then collects the objects
>> returned by the initialiser and adds them to the list that is returned by
>> createFood().
>
> I really hate when students (and I assume is is a homework/tutorial
> exercise) get asked to write bad code. This function should be
> entirely unnecessary.
It were unnecessary if it should create a single instance. For a whole list
I think it's fine -- except that the name is misleading.
> The function for creating instances is the
> constructor - it's already written. We don't need another.
>
> And the Pythonic way of building lists is a list comprehension.
> So this whole exercise should be reduced to:
>
> food_list = [Food(t) for t in tuple_list]
You forgot the * which I think is an advanced and even somewhat questionable
feature.
To go to the other end of the spectrum of possible solutions, the teacher
may well see attempts like
def create_food_list(pairs):
for i in range(len(pairs)):
name = pairs[i][0]
taste = pairs[i][1]
food = Food(name, taste)
pairs[i] = food
return pairs
which gives opportunities to show
- idiomatic iteration
- tuple unpacking
- good ways for a function to communicate with its caller.
You may argue that this should have been taught before starting with custom
objects...
> If we are going to teach objects lets use the objects!
More information about the Tutor
mailing list