Skip to main content
 首页 » 编程设计

python之如何在模块中搜索函数/类

2025年05月04日11emanlee

我想知道某个函数/类是否存在于某个模块中。 我确实知道如何使用 dir() 生成模块上层/层次结构中所有类/函数的列表 例如,假设我想知道函数 now() 是否存在于 datetime 模块中:

import datetime 
dir(datetime) 

但这并没有列出函数now(),因为now()包含在更深层次(在datetime.datetime中到准确)。如何检查 now() 是否存在? 或者也许有一种方法可以列出所有级别的所有内容?

请您参考如下方法:

这段代码递归地列出了模块的内容。但是请注意,如果两个子模块/对象/...共享相同的名称,它将失败

import time 
import datetime 
 
pool=[] # to avoid loops  
 
def recdir(d,n=''): 
    children_all=dir(d) 
    children=[c for c in children_all if c[0]!='_' and not c in pool] 
    for child in children: 
        pool.append(child) 
        full_name=n+"."+child 
        print "Found: ","'"+full_name+"' type=",eval("type("+full_name+")") 
        string="recdir(d."+child+",'"+full_name+"')" 
        print "Evaluating :",string 
        time.sleep(0.2) 
        eval(string) 
 
recdir(datetime,'datetime')