在python中检索非内置函数

时间:2012-02-12 12:47:02

标签: python

python中的“dir()”函数检索类的所有属性。我想知道是否有类似的函数只返回用户定义的函数?谢谢!

1 个答案:

答案 0 :(得分:3)

如果你想从用户定义的函数告诉内置函数,我会使用types模块。 例如:

>>> def hello():
...     print("hi")
... 
>>> import types
>>> type(hello) is types.BuiltinFunctionType
False
>>> type(hello) is types.FunctionType
True

然后它取决于你想做什么。你可以使用列表推导来检查一个类的所有属性,并只保留那些结果为真的。

[ x for x in dir(yourclass) if (type(x) is types.FunctionType) ]

希望它有所帮助。