python全局变量__name__(一个新手问题)

时间:2011-06-14 22:06:49

标签: python

首次启动python shell时,有以下名称是什么?它们看起来不像__builtins__

中的函数
>>> dir(__name__)

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', 
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
 '__mod__', '__mul__', '__ne__', '__new__', '__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']

2 个答案:

答案 0 :(得分:8)

__name__是一个字符串,它是一个字符串方法。它是模块的名称或顶部的'__main__'。因此,这个成语经常出现:

if __name__ == '__main__':
    # this file was called directly, not imported
    main()

答案 1 :(得分:5)

dir(__name__)显示__name__的属性,由于__name__是字符串,因此它显示str类的属性。大多数列出的属性都是方法。您可以使用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.