2

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

import datetime
dir(datetime)

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

4

1 回答 1

1

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

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')
于 2013-09-20T11:52:54.820 回答