在Python中导入类
我只是想知道为什么
import sys
exit(0)
会给我这个错误:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in ?
exit(0)
TypeError: 'str' object is not callable
但是
from sys import exit
exit(0)
却能正常工作呢?
3 个回答
0
好的,从你的回答中我可以记得:
import sys from *
这行代码会把sys模块里的所有内容都导入进来。
6
可以查看 http://effbot.org/zone/import-confusion.htm 来了解在Python中使用 import
的各种方式。
import sys
这行代码是把sys模块导入进来,并把它的名字叫做“sys”,这样你就可以在你的代码中使用它了。不过,像“exit”这样的功能并不会直接出现在你的代码里,但你可以这样访问它:
sys.exit(0)
from sys import exit
这行代码是把sys模块中特定的功能导入到你的代码里。具体来说,它把“exit”这个名字绑定到sys.exit这个功能上。
exit(0)
要查看你当前的命名空间里有什么,可以使用 dir
这个函数。
>>> import sys
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>>
>>> from sys import exit
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'exit', 'sys']
你甚至可以查看sys模块里都有什么内容:
>>> dir(sys)
['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']
8
Python只把你选择的名字放进命名空间里。
你可以用下面这个方法来实现相同的效果:
sys.exit(0)
因为import sys
只把sys
这个关键词放进了当前的命名空间。