Python 内建函数 - dir([object])

本文详细介绍了Python内置函数dir()的工作原理及其使用方法。包括无参数时返回当前作用域的变量名列表,有参数时返回对象的有效属性列表。此外还探讨了dir()如何处理不同类型的对象,如模块、类及自定义对象等。

Manual

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.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

  • If the object is a module object, the list contains the names of the module’s attributes.
  • If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
  • Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

The resulting list is sorted alphabetically. For example:

>>>
>>> import struct
>>> dir()   # show the names in the module namespace
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
Note Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

直译

无参数时,返回当前局部域的变量名列表。有参数时,则尝试返回该对象的有效属性列表。
如果object有命名的__dir__()方法,那么该方法将会被调用,且必须返回属性列表。这允许对象通过实现自定__getattr__()或__getattribute__()函数,来自定义dir()报告其属性的方式。
如果对象没有提供__dir__(),该函数会尽最大努力尝试联合对象的__dict__ 属性(如果定义了)和它的类型对象的信息,但结果列表不一定完整,当对象有自定义__getattr__()时也有可能不准确。
默认的dir()机制在不同对象类型上表现不同,相比完整度、信息性,它会尝试生成最大关联度:

  • 如果object是模块对象,列表则包含模块的属性名;
  • 如果object是类型或类对象,列表会包含它的属性名,且递归它的基类属性;
  • 其它,列表会包含对象的属性名、类属型名,并递归它类的基类属性。

结果列表按字母顺序排序,例如:

>>>
>>> import struct
>>> dir()   # 显示模块域名内的命名
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # 显示struct模块内的命名
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
注意:因为dir()主要为了便于交互式提示而提供,所以相比让它提供一组严格或规范定义的命名集,它会试图提供一组不够严肃的命名集,并且它的细节行为可能会因版本而改变,例如:当参数是一个类时,其元类属性并不在结果列表中。

实例

>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

>>> import os
>>> dir(os)
['F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fstat', 'fsync', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']

>>> class 优快云:
    def foobar(self):
        print('Hello 优快云er')       
>>> dir(优快云)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'foobar']

>>> def csdn(x):
    print('Hello ', x)  
>>> dir(csdn)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

拓展阅读

__dir__()
__getattr__()
__dict__

<think>好的,我现在需要介绍Pythondir()内置函数。首先,我得回想一下自己对dir()的理解。dir()函数主要用于返回对象的有效属性列表,如果没有参数,则返回当前作用域内的名称列表。这个函数在调试和探索对象结构非常有用,比如看模块、类或实例有哪些属性和方法。 用户可能已经知道一些基本用法,但可能需要更详细的解释,包括参数、返回值、使用场景和示例。我应该先明确函数的定义,然后分点说明其功能,再举例说明不同情况下的用法,比如不带参数、带参数的情况,以及如何处理不同类型的对象。 要注意的是,dir()返回的列表是字母顺序排列的,这可能对用户有帮助。另外,dir()的行为在不同对象下可能不同,因为它是调用对象的__dir__()方法,如果存在的话。这一点需要特别指出,以免用户误解结果。 可能需要提到,dir()常用于交互式环境中,比如在Python shell中快速对象的结构。对于新手来说,这是一个方便的工具,可以避免频繁阅文档。但同也要提醒用户,dir()返回的属性可能包括魔术方法(如__init__)和私有方法(以双下划线开头),需要自行筛选有用的信息。 另外,对比其他相关函数,比如help()或vars(),可以帮助用户更好地理解dir()的独特作用。例如,help()提供详细的文档,而dir()提供属性列表,两者结合使用更高效。 接下来,我需要组织内容的结构。首先定义dir()函数,然后参数说明,返回值,使用示例,注意事项,以及与其他函数的比较。要确保语言简洁,例子清晰,避免技术术语过多,但必要解释清楚。 可能遇到的问题包括用户不清楚何使用dir(),或者返回的结果中包含大量不熟悉的属性。这候需要强调dir()的探索性质,以及如何结合其他工具(如文档或help())来进一步理解这些属性。 最后,总结dir()的主要用途,比如调试、学习新模块、检对象结构等,帮助用户形成整体的认识。</think>--- ### **Python `dir()` 函数详解** --- #### **1. 核心功能** `dir()` 是Python的内置函数,**用于探索对象的属性和方法**。其核心作用: - **无参数调用**:返回当前作用域内的变量、函数、类等名称列表 - **带参数调用**:返回指定对象的有效属性列表(包括方法、数据属性等) - **交互式调试**:快速对象结构,辅助开发调试 --- #### **2. 函数定义** ```python dir([object]) -> list ``` - **参数**: - `object` (可选):任意Python对象(模块、类、实例、基本类型等) - **返回值**: 排序后的字符串列表(按字母顺序) --- #### **3. 使用场景** **场景1:看当前作用域** ```python a = 10 def test(): pass print(dir()) # 输出:['__annotations__', '__builtins__', ..., 'a', 'test'] ``` **场景2:探索模块内容** ```python import math print(dir(math)[:5]) # 输出:['__doc__', '__loader__', '__name__', '__package__', '__spec__'] ``` **场景3:分析类结构** ```python class MyClass: def __init__(self): self.x = 1 def show(self): print(self.x) print(dir(MyClass)) # 输出包含:['__class__', '__delattr__', ..., 'show'] ``` **场景4:检实例属性** ```python obj = MyClass() print(dir(obj)) # 包含实例属性x和继承的方法 ``` --- #### **4. 运行机制** -对象定义了 `__dir__()` 方法,`dir()` 调用该方法返回结果 - 默认行为: - 对于模块对象:返回模块的 `__dict__` 属性(过滤掉非公开成员) - 对于类/实例:递归收集所有基类属性 --- #### **5. 实用技巧** **技巧1:过滤魔术方法** ```python [name for name in dir(str) if not name.startswith('__')] # 输出:['capitalize', 'casefold', 'center', ...] ``` **技巧2:与getattr()配合使用** ```python obj = "hello" for name in dir(obj): attr = getattr(obj, name) print(f"{name}: {type(attr)}") ``` **技巧3:调试快速补全** 在交互式环境中,输入 `object.` + `Tab` 键的自动补全功能底层即使用 `dir()` --- #### **6. 注意事项** 1. **非完整列表**:结果可能不包含动态生成的属性 2. **名称修饰**:私有属性(`__var`)会被重命名为 `_ClassName__var` 3. **性能影响**:对大型对象频繁调用可能影响性能 4. **与help()的区别**: - `dir()` 展示属性名列表 - `help()` 显示详细文档说明 --- #### **7. 扩展应用** **自定义`__dir__`方法** ```python class CustomDir: def __dir__(self): return ['name', 'value', 'custom_method'] obj = CustomDir() print(dir(obj)) # 输出自定义列表 ``` **与inspect模块对比** ```python import inspect # 获取更详细的成员信息 inspect.getmembers(str) # 返回(名称,值)元组列表 ``` --- ### **典型示例对比** | 对象类型 | dir() 输出特点 | 示例输出片段 | |----------------|-------------------------------------|----------------------------------| | 基本类型(int) | 包含数值操作方法 | `['bit_length', 'conjugate', ...]` | | 模块(sys) | 包含模块级变量/函数 | `['api_version', 'argv', ...]` | | 自定义类实例 | 包含实例属性+类继承的方法 | `['__class__', 'x', 'show']` | | 函数对象 | 显示函数特有属性 | `['__annotations__', '__call__', ...]` | --- ### **总结** `dir()` 是Python开发者必备的探索工具: - **学习阶段**:快速了解未知对象的可用接口 - **调试阶段**:验证对象是否包含预期属性 - **开发阶段**:辅助实现反射等动态编程技术 配合 `help()`、`type()` 和 `inspect` 模块使用,可显著提升代码探索效率。建议在以下场景优先使用: 1. 交互式环境调试 2. 处理第三方库的未知对象 3. 实现动态属性访问功能
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值