Concise Python tutorial |
Chapter 4 modules |
Previous Page |
Dir () function |
Next Page |
Dir () function
You can use the built-indir
Function to list the identifier defined by the module. Identifiers include functions, classes, and variables.
When youdir()
When a module name is provided, it returns the list of module-defined names. If no parameter is provided, it returns the name list defined in the current module.
Use the Dir Function
Example 8.4 use the Dir Function
$ python
>>> import sys
>>> dir(sys) # get list of attributes for sys module
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
'builtin_module_names', 'byteorder', 'call_tracing', 'callstats',
'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type',
'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval',
'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding',
'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
'meta_path','modules', 'path', 'path_hooks', 'path_importer_cache',
'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
'version', 'version_info', 'warnoptions']
>>> dir() # get list of attributes for current module
['__builtins__', '__doc__', '__name__', 'sys']
>>>
>>> a = 5 # create a new variable 'a'
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'sys']
>>>
>>> del a # delete/remove a name
>>>
>>> dir()
['__builtins__', '__doc__', '__name__', 'sys']
>>>
How it works
First, let's take a look atsys
Module usagedir
. We can see that it contains a huge list of attributes.
Next, we will notdir
Use the function to PASS Parameters -- by default, it returns the attribute list of the current module. Note that the input module is also part of the list.
To observedir
To define a new variable.a
And assign a value to it, and then testdir
, We can see that the above values are added to the list. We usedel
Statement to delete the variables/attributes of the current module. This change is again reflected indir
.
Aboutdel
A note -- this statement is used after runningDeleteA variable/name. In this example,del a
You will no longer be able to use variablesa
-- It is as if it has never existed before.
Previous Page |
Level 1 |
Next Page |
Create your own modules |
Homepage |
Summary |