[Tutor] Can anyone help answer this?

Alan Gauld alan.gauld at yahoo.co.uk
Wed Jun 10 05:51:33 EDT 2020


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. 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]

If we are going to teach objects lets use the objects!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list