Python中文网

Python dir() 函数

cnpython2379

版本 E:\Projects\testTool>python --version Python 3.6.2

先看看官网上是怎么描述dir()函数的: Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object. 翻译过来就是: 如果不向dir()提供参数,返回当前范围的名称列表,带参数时,返回参数的名称列表。 示例

直接调用dir()

dir() ['annotations', 'builtins', 'doc', 'loader', 'name', 'package', 'spec']

在当前模块引入一个包

dir() ['annotations', 'builtins', 'doc', 'loader', 'name', 'package', 'spec', 'sys']

执行后的结果包含了引入的包的名字 3.获得sys模块的属性

dir(sys) ['displayhook', 'doc', 'excepthook', 'interactivehook', 'loader', 'name', 'package', 'spec', 'stderr', 'stdin', 'stdout', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'set_asyncgen_hooks', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']

4.在当前模块添加一个变量

a = 5 #创建了一个新变量

dir() ['annotations', 'builtins', 'doc', 'loader', 'name', 'package', 'spec', 'a', 'sys']

5.在当前模块添加一个函数

def function():pass #添加一个函数

dir() ['annotations', 'builtins', 'doc', 'loader', 'name', 'package', 'spec', 'a', 'function', 'sys']

6.在当前模块添加一个类

class Testcls(): #新建一个类 ... def init(self): ... self.a = 1 ... self.b = 2 ... def add_func(self): ... return self.a + self.b

dir() ['Testcls', 'annotations', 'builtins', 'doc', 'loader', 'name', 'package', 'spec', 'a', 'function', 'sys']

查看类Testcls的属性:

dir(Testcls) ['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'add_func']

总结 通过以上的示例,python提供的dir()函数,其实就是查看当前域的变量、方法和类,在我们不知道一个模块或库或类有哪些属性时,使用dir()很方便。

上一篇:没有了

下一篇:Python help() 函数