dir() 函数
dir() 是 Python 的内置函数,用于查看对象的属性和方法。它是探索未知对象、调试代码的有力工具,尤其在交互式解释器中非常有用。
不带参数的 dir()
a = 10
b = "hello"
def func():
pass
print dir() # ['__builtins__', '__doc__', '__name__', 'a', 'b', 'func']
不带参数时,dir() 返回当前作用域中定义的所有名称列表。这在交互式解释器中特别方便,可以查看当前定义了哪些变量和函数。
查看模块内容
import math
print dir(math)
# ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', ...]
dir(module) 返回模块中定义的所有公开名称(包括函数、常量、类)。
查看对象的方法
s = "hello"
print dir(s)
# ['__add__', '__class__', '__contains__', ... 'capitalize', 'center', 'count', ...]
dir(object) 返回对象的所有属性和方法,包括以双下划线开头的特殊方法。
过滤双下划线名称
通常只关心普通方法,可以过滤掉 __xxx__:
s = "hello"
print [m for m in dir(s) if not m.startswith('_')]
# ['capitalize', 'center', 'count', 'decode', 'encode', 'endswith', ...]
与 help() 配合
dir() 列出名称,help() 查看详细说明:
import os
# 先看有哪些方法
print dir(os.path)
# 再看具体用法
help(os.path.join)
# join(a, *p)
# Join two or more pathname components, inserting '/' as needed.
自定义 dir() 行为
类可以定义 __dir__() 方法来控制 dir() 的返回:
class MyClass(object):
def __init__(self):
self.public = 1
self._private = 2
self.__mangled = 3
def __dir__(self):
return ["public", "custom_method"]
obj = MyClass()
print dir(obj) # ['custom_method', 'public']
实际应用
探索新模块:
import urllib2
print [m for m in dir(urllib2) if not m.startswith('_')]
# ['AbstractBasicAuthHandler', 'AbstractDigestAuthHandler', ...]
查找特定方法:
# 查找字符串中以 'is' 开头的方法
s = "hello"
print [m for m in dir(s) if m.startswith('is')]
# ['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
检查对象是否支持某方法:
def has_method(obj, name):
return name in dir(obj)
print has_method("hello", "split") # True
print has_method(42, "split") # False
注意:dir() 返回的是对象当前可用的名称,不保证包含所有可能的属性(如动态生成的属性)。对于严格的属性检查,用 hasattr() 更可靠:
print hasattr("hello", "split") # True
print hasattr(42, "split") # False