开发者

importing classes python

开发者 https://www.devze.com 2023-01-03 04:46 出处:网络
Ju开发者_如何学运维st wondering why import sys exit(0) gives me this error: Traceback (most recent call last):

Ju开发者_如何学运维st wondering why

import sys
exit(0)

gives me this error:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in ?
    exit(0)
TypeError: 'str' object is not callable

but

from sys import exit
exit(0)

works fine?


Python imports only the chosen names into the namespace.

Your equivalent first solution should be

sys.exit(0)

since import sys imports only the sys keyword into the current namespace.


See http://effbot.org/zone/import-confusion.htm for all the different ways to use import in Python.

import sys

This imports the sys module and binds it to the name "sys" in your namespace. "exit", and other members of the sys module are not brought into the namespace directly but can be accessed like so:

sys.exit(0)

from sys import exit

This imports specific members of the sys module into your namespace. Specifically this binds the name "exit" to the sys.exit function.

exit(0)

To see what's in your namespace, use the dir function.

>>> import sys
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>>
>>> from sys import exit
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'exit', 'sys']

You can even see what all is in the sys module itself:

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


Ok from your Answers I can remeber that:

import sys from *

would import all members from sys

0

精彩评论

暂无评论...
验证码 换一张
取 消