给定一个任何类型的Python对象,是否有一种简单的方法来获得该对象拥有的所有方法的列表?

或者如果这是不可能的,是否至少有一种简单的方法来检查它是否具有特定的方法,而不是在调用方法时检查是否发生错误?


当前回答

可以创建一个getAttrs函数,该函数将返回对象的可调用属性名

def getAttrs(object):
  return filter(lambda m: callable(getattr(object, m)), dir(object))

print getAttrs('Foo bar'.split(' '))

那就回来

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
 '__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__', 
 '__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__', 
 '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', 
 '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', 
 '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', 
 '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 
 'remove', 'reverse', 'sort']

其他回答

最简单的方法是使用dir(objectname)。它将显示该对象的所有可用方法。

获取任何对象的方法列表的最简单方法是使用help()命令。

help(object)

它将列出与该对象相关的所有可用/重要方法。

例如:

help(str)

假设我们有一个Python obj。然后查看它拥有的所有方法,包括那些被__包围的方法(魔术方法):

print(dir(obj))

要排除魔法内置,可以这样做:

[m for m in dir(obj) if not m.startswith('__')]

如果你特别需要方法,你应该使用inspect.ismethod。

对于方法名:

import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]

对于方法本身:

import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]

有时检查。isroutine也很有用(对于内置,C扩展,没有“binding”编译器指令的Cython)。

这里有一个很好的一行代码(但也会得到属性):

print(*dir(obj), sep='\n')