Python dir() 函数
dir() 是 Python 中用于获取对象属性和方法列表的内置函数。
dir() 返回一个包含对象所有属性和方法名称的列表。这个函数在探索未知对象、调试代码、了解类结构时非常有用。
单词释义: dir 是 directory(目录)的缩写,这里指属性和方法的列表。
基本语法与参数
语法格式
dir(object) dir()
参数说明
- 参数 object(可选):
- 类型: 任意对象
- 描述: 要获取属性列表的对象。如果不传参数,返回当前作用域的名称列表。
函数说明
- 返回值: 返回一个字符串列表,包含属性和方法的名称。
- 特点: 列表按字母顺序排序。
实例
示例 1:查看对象的属性
实例
# 查看列表的所有属性和方法
print(dir([]))
# 输出: ['__add__', '__class__', '__contains__', ... 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
# 查看字符串的属性
print(dir(""))
# 输出: ['__add__', '__class__', '__contains__', ... 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# 查看字典的属性
print(dir({}))
# 输出: ['__class__', '__contains__', ... 'clear', 'copy', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
print(dir([]))
# 输出: ['__add__', '__class__', '__contains__', ... 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
# 查看字符串的属性
print(dir(""))
# 输出: ['__add__', '__class__', '__contains__', ... 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# 查看字典的属性
print(dir({}))
# 输出: ['__class__', '__contains__', ... 'clear', 'copy', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
运行结果预期:
返回对象的所有属性和方法名称列表。
代码解析:
- 以双下划线
__开头的是特殊属性/方法(magic methods)。 - 不带双下划线的是公开的方法,如
append,sort等。
示例 2:查看自定义类的属性
实例
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
# 创建实例
p = Person("Tom", 20)
# 查看实例的属性
print(dir(p))
# 输出: ['__class__', '__delattr__', '__dict__', '__init__', ... 'age', 'greet', 'name']
# 过滤只显示非特殊方法
attrs = [attr for attr in dir(p) if not attr.startswith('_')]
print(attrs) # 输出: ['age', 'greet', 'name']
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
# 创建实例
p = Person("Tom", 20)
# 查看实例的属性
print(dir(p))
# 输出: ['__class__', '__delattr__', '__dict__', '__init__', ... 'age', 'greet', 'name']
# 过滤只显示非特殊方法
attrs = [attr for attr in dir(p) if not attr.startswith('_')]
print(attrs) # 输出: ['age', 'greet', 'name']
运行结果预期:
['__class__', '__delattr__', '__dict__', '__init__', ... 'age', 'greet', 'name'] ['age', 'greet', 'name']
代码解析:
__dict__包含对象的实例属性。- 过滤
__开头的方法可以得到公开属性。
示例 3:不带参数使用
实例
# 不带参数,返回当前作用域的名称列表
print(dir())
# 输出: ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
# 导入模块后查看
import os
print(dir())
# 会包含 'os' 在列表中
# 查看模块的属性
import json
print(dir(json))
# 输出: ['JSONDecodeError', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads', 'tool']
print(dir())
# 输出: ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
# 导入模块后查看
import os
print(dir())
# 会包含 'os' 在列表中
# 查看模块的属性
import json
print(dir(json))
# 输出: ['JSONDecodeError', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads', 'tool']
运行结果预期:
返回当前作用域中可用的名称列表。
dir() 是探索 Python 对象和模块的强大工具,特别适合交互式学习和调试。
Python3 内置函数
点我分享笔记