On 14/05/13 02:21, Stafford Baines wrote:
Please explain the significance of __some term__.  For example  __name__ as
in

If __name__ == '__main__':

   main()



When is the under, under used?


Underscores are legal characters in names. So you can write:

some_term = whatever()

and it is a legal name.

*Leading* underscores have a special meaning. A single leading underscore is considered 
to be "private":

_name = 42

means that _name should be considered "private, hands off". Or at least, "if you 
break it, you bought it". No guarantees are valid if you change a private value and things 
break.

Names with Double leading and trailing UNDERscores ("dunder") are reserved for 
Python's internal use. They get used for special methods, and a few other things. For 
example, to override the + operator, you write a class that defines __add__ and __radd__ 
methods. To override the == operator, you write a class that defines a __eq__ method. 
There are many examples of such, you can read the docs for a current list:

http://docs.python.org/2/reference/datamodel.html#special-method-names


__name__ is a special variable automatically created by Python. Modules and packages are 
automatically given a variable called __name__ which contains their name. When you are 
executing a module as a script, that variable gets set to the special value 
"__main__" instead of the module's actual name. So you can detect whether your 
code is being run as a script with a tiny bit of boilerplate code:


if __name__ == '__main__':
    ...


--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to