and the program is run as: python /usr/lib/python/person.py
class Person: def __init__(self): pass def getAge(self): print __name__ p = Person() p.getAge()
class Person: def __init__(self): pass def getAge(self): print __name__ p = Person() p.getAge()
Person
getAge
usr.lib.python.person
__main__
在 Python2 的解释环境下,正确的输出应该为:__main__
题目本身排版有误,最后两条语句不能放在同一行,直接运行报语法错误:
SyntaxError: invalid syntax
运行正确的排版应该为:
class Person:
def __init__(self):
pass
def getAge(self):
print __name__
p = Person()
p.getAge()
以上代码作为脚本文件运行时(而不是作为模块被引用),将输出
__main__,详情可参考官方文档:
'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:
if __name__ == "__main__": # execute only if run as a script main()
For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.
class Person: def __init__(self): pass def getAge(self): print(__name__) p = Person() p.getAge()考查内置变量__name__:
class Person: def __init__(self): pass def getAge(self): print(__name__) if __name__ == '__main__': p = Person() p.getAge()train_Flickr_LDL.py:
import train_FI if __name__ == '__main__': p = train_FI.Person() p.getAge()当运行train_FI.py时,输出结果为__main__:train_FI.py模块被直接执行,所以它的内置变量__name__的值就是__main__
__main__ math