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

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


当前回答

如果你特别需要方法,你应该使用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)。

其他回答

...除了简单地检查调用方法时是否发生错误之外,是否至少有一种简单的方法来检查它是否具有特定的方法

虽然“请求原谅比请求允许更容易”肯定是python的方式,但你可能在寻找:

d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
    d.get('foo')
# OUT: 'bar'

你可以使用Python中预定义的dir()。

import module_name
dir(module_name)

你也可以把一个对象传递给dir() as

dir(object_name)

如果对象是预定义类(如int、str等)的对象,则会显示其中的方法(您可能知道这些方法是内建函数)。如果该对象是为用户定义的类创建的,它将显示该类中给出的所有方法。

对于许多对象,你可以使用这段代码,用你感兴趣的对象替换'object':

object_methods = [method_name for method_name in dir(object)
                  if callable(getattr(object, method_name))]

我发现它在diveintopython.net(现在存档),应该提供一些进一步的细节!

如果你得到一个AttributeError,你可以用这个代替:

getattr()不允许pandas风格的Python 3.6抽象虚拟子类。这段代码执行与上面相同的操作,并忽略异常。

import pandas as pd
df = pd.DataFrame([[10, 20, 30], [100, 200, 300]],
                  columns=['foo', 'bar', 'baz'])
def get_methods(object, spacing=20):
  methodList = []
  for method_name in dir(object):
    try:
        if callable(getattr(object, method_name)):
            methodList.append(str(method_name))
    except Exception:
        methodList.append(str(method_name))
  processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s)
  for method in methodList:
    try:
        print(str(method.ljust(spacing)) + ' ' +
              processFunc(str(getattr(object, method).__doc__)[0:90]))
    except Exception:
        print(method.ljust(spacing) + ' ' + ' getattr() failed')

get_methods(df['foo'])
import moduleName
for x in dir(moduleName):
    print(x)

这应该工作:)

在更直接的答案之上,如果我没有提到IPython,那就是我的疏忽。

按Tab键查看可用的方法,自动补全。

一旦你找到了一个方法,试试:

help(object.method)

查看pydocs、方法签名等。

啊…REPL。