dir() 函数是 Python 内置函数,用于返回指定对象的有效属性列表。如果没有提供参数,则返回当前局部作用域的属性列表。

以下是 dir() 函数的语法:
dir([object])

  •  object:可选,要查询的对象。如果省略,则返回当前局部作用域的属性列表。


下面是一些示例:
# 使用 dir() 查询模块的属性
import math

module_attributes = dir(math)
print(module_attributes)
# 输出包含 math 模块所有属性和方法的列表

# 使用 dir() 查询内置对象的属性
string_attributes = dir("Hello")
print(string_attributes)
# 输出包含字符串对象所有属性和方法的列表

# 使用 dir() 查询自定义对象的属性
class MyClass:
    def __init__(self):
        self.my_attribute = 42

    def my_method(self):
        pass

my_instance = MyClass()
instance_attributes = dir(my_instance)
print(instance_attributes)
# 输出包含自定义对象实例的属性和方法的列表

在这些示例中,dir() 函数被用于查询模块、字符串和自定义对象实例的属性和方法。返回的列表包含了对象的所有有效属性和方法的名称。需要注意,dir() 返回的列表中可能包含一些以双下划线 __ 开头和结尾的特殊方法,这些方法在 Python 中具有特殊用途。


转载请注明出处:http://www.zyzy.cn/article/detail/333/Python3