[Tutor] Using Class Properly - early beginner question

boB Stepp robertvstepp at gmail.com
Fri Mar 24 17:41:39 EDT 2017


I'm forwarding this to Tutor.  Please respond to the whole group and
not just me personally, so you can have access to the experts as well
as allowing all of us learners the opportunity to learn more.  I can't
respond now, but will try to do so later.

On Fri, Mar 24, 2017 at 6:51 AM, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> Thank you so much for your help.
> I have a question: When creating an instance of GroceryListMaker, you are using:
>
> if __name__ == "__main__":
>
> What is that specifically for?
> I tested your code and both worked, with and without
> if __name__ == "__main__":
>
> a)
>
> if __name__ == "__main__":
>     my_shopping_list = GroceryListMaker()
>     my_shopping_list.make_shopping_list()
>     my_shopping_list.display_shopping_list()
>
> b)
>
> my_shopping_list = GroceryListMaker()
> my_shopping_list.make_shopping_list()
> my_shopping_list.display_shopping_list()
>
> Can you explain?
> Thanks :)
>
>> class GroceryListMaker:  # Explicit inheritance from "object" is
>> optional in Py 3.
>>     def __init__(self):
>>         self.shopping_list = []
>>         self.prompt = ('What food items would you like to buy?\n(Type "quit"'
>>                 ' to exit):  ')
>>
>>     def make_shopping_list(self):
>>         while True:
>>             food = input(self.prompt)
>>             if food == 'quit':
>>                 break
>>             else:
>>                 self.shopping_list.append(food)
>>
>>     def display_shopping_list(self):
>>         print('\n\nYour shopping list now has the following items:\n')
>>         for item_number, item in enumerate(self.shopping_list):
>>             print('%s.  %s' % (item_number, item))
>>
>> if __name__ == '__main__':
>>     my_shopping_list = GroceryListMaker()
>>     my_shopping_list.make_shopping_list()
>>     my_shopping_list.display_shopping_list()



-- 
boB


More information about the Tutor mailing list