Python dir() 内置函数

来自 Python 3 文档

不带参数时,返回当前局部作用域中的名称列表。带参数时,尝试返回该对象的所有有效属性列表。

简介

Python 中的 dir() 函数是一个强大的内置函数,它返回当前命名空间中的名称列表或给定对象的属性列表。它常用于内省和探索对象、模块和类,帮助您发现可以使用的可用方法、属性和名称。

语法

dir([object])
  • object (可选): 您希望探索其属性的对象。如果未提供,则返回当前命名空间中的名称。

探索当前命名空间中的名称

a = 10
b = "Hello"
def my_function():
    pass

print(dir())
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'my_function']

探索模块属性

import math
print(dir(math))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', ... ]

探索对象属性

class MyClass:
    def __init__(self):
        self.x = 5
        self.y = "Hello"

obj = MyClass()
print(dir(obj))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', ... 'x', 'y']

dir() 与内置类型一起使用

my_list = [1, 2, 3]
print(dir(my_list))
[..., 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

过滤 dir() 输出

import math
print([name for name in dir(math) if not name.startswith("__")])
['acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', ... ]

相关链接