python global variable __name__ (a newbie question)
What are the following names when I first start my python shell? They do not look like functions from __builtins__
:
>>> dir(__name__)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__n开发者_如何学Pythonew__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', '_formatter_field_name_split', '_formatter_parser',
'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace',
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']
__name__
is a string and those a string methods. It's the name of the module or '__main__'
on the toplevel. Hence this idiom appears often:
if __name__ == '__main__':
# this file was called directly, not imported
main()
dir(__name__)
shows the attributes of __name__
, and since __name__
is a string, it shows the attributes of the str
class. Most of the listed attributes are methods. You can get more information using help()
:
>>> help(str.index)
Help on method_descriptor:
index(...)
S.index(sub [,start [,end]]) -> int
Like S.find() but raise ValueError when the substring is not found.
精彩评论