因为可以在Python中调用所有(甚至字段),所以我不确定是否有内置函数仅列出方法 . 您可能想尝试通过 dir 获得的对象是否为callable .
149
没有外部库的Python 3.x答案
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
被排除在外的结果:
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]
12
试试这个属性 __dict__ .
-1
您还可以从类型中导入FunctionType并使用 class.__dict__ 进行测试:
from types import FunctionType
class Foo:
def bar(self): pass
def baz(self): pass
def methods(cls):
return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
methods(Foo) # ['bar', 'baz']
2
我知道这是一个旧帖子,但只是写了这个函数,并将留在这里是案件有人绊倒寻找答案:
def classMethods(the_class,class_only=False,instance_only=False,exclude_internal=True):
def acceptMethod(tup):
#internal function that analyzes the tuples returned by getmembers tup[1] is the
#actual member object
is_method = inspect.ismethod(tup[1])
if is_method:
bound_to = tup[1].im_self
internal = tup[1].im_func.func_name[:2] == '__' and tup[1].im_func.func_name[-2:] == '__'
if internal and exclude_internal:
include = False
else:
include = (bound_to == the_class and not instance_only) or (bound_to == None and not class_only)
else:
include = False
return include
#uses filter to return results according to internal function and arguments
return filter(acceptMethod,inspect.getmembers(the_class))
10 回答
如果您的方法是"regular"方法而不是
statimethod
,classmethod
等 .我想出了一点点黑客 -
for k, v in your_class.__dict__.items(): if "function" in str(v): print(k)
通过相应地更改
if
条件中的"function",可以将其扩展到其他类型的方法 .在python 2.7上测试过 .
假设您想知道与列表类关联的所有方法Just Type以下内容
上面将为您提供列表类的所有方法
请注意,您需要考虑是否需要结果中包含的继承(但未覆盖)的基类方法 .
dir()
和inspect.getmembers()
操作确实包含基类方法,但__dict__
属性的使用不包括 .所以
想想Python第210页
一个例子(列出
optparse.OptionParser
类的方法):请注意
getmembers
返回2元组列表 . 第一项是成员的名称,第二项是值 .您还可以将实例传递给
getmembers
:有
dir(theobject)
方法列出对象的所有字段和方法(作为元组)和inspect模块(作为代码编写),用文档列出字段和方法(在“”中) .因为可以在Python中调用所有(甚至字段),所以我不确定是否有内置函数仅列出方法 . 您可能想尝试通过
dir
获得的对象是否为callable .没有外部库的Python 3.x答案
被排除在外的结果:
试试这个属性
__dict__
.您还可以从类型中导入FunctionType并使用
class.__dict__
进行测试:我知道这是一个旧帖子,但只是写了这个函数,并将留在这里是案件有人绊倒寻找答案: