簡體   English   中英

導入類python

[英]importing classes 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)

工作正常?

Python僅將所選名稱導入命名空間。

你應該得到同等的第一個解決方

sys.exit(0)

因為import sys只將sys關鍵字導入當前命名空間。

有關在Python中使用import所有不同方法,請參閱http://effbot.org/zone/import-confusion.htm

導入系統

這將導入sys模塊並將其綁定到命名空間中的名稱“sys”。 “exit”,sys模塊的其他成員不會直接進入命名空間,但可以這樣訪問:

sys.exit(0)

來自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']

從您的答案中確定我可以記住:

import sys from *

將從sys導入所有成員

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM