[Tutor] Using Class Properly - early beginner question

Alan Gauld alan.gauld at yahoo.co.uk
Fri Mar 24 21:32:52 EDT 2017


On 24/03/17 21:41, boB Stepp wrote:

>> I have a question: When creating an instance of GroceryListMaker, you are using:
>>
>> if __name__ == "__main__":
>>
>> What is that specifically for?

Its a common trick in Python that enables a single file to
act as both a module and a program. When a script is imported
Python sets its __name__ attribute to the name of the module.
When a script is executed directly Python sets its __name__
to __main__.

Thus

>> if __name__ == "__main__":
>>     my_shopping_list = GroceryListMaker()
>>     my_shopping_list.make_shopping_list()
>>     my_shopping_list.display_shopping_list()

Means only execute the three indented lines if running the file
directly, do not execute them if the file is being imported.

Whereas:

>> my_shopping_list = GroceryListMaker()
>> my_shopping_list.make_shopping_list()
>> my_shopping_list.display_shopping_list()

will result in the three lines being executed regardless of
whether the file is imported or executed directly.

You will see this idiom in many files even when they
are not intended to be run directly because it is
common to create a tests or a demonstration that
will run when executed directly.

HTH
-- 
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