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

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


当前回答

对于许多对象,你可以使用这段代码,用你感兴趣的对象替换'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'])

其他回答

这里指出的所有方法的问题是,您不能确定某个方法不存在。

在Python中,您可以通过__getattr__和__getattribute__拦截点调用,从而可以在“运行时”创建方法。

例子:

class MoreMethod(object):
    def some_method(self, x):
        return x
    def __getattr__(self, *args):
        return lambda x: x*2

如果你执行它,你可以调用对象字典中不存在的方法…

>>> o = MoreMethod()
>>> o.some_method(5)
5
>>> dir(o)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'some_method']
>>> o.i_dont_care_of_the_name(5)
10

这就是为什么在Python中使用“请求原谅比请求许可更容易”的范例。

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

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

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

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

print(dir(obj))

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

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

我已经完成了下面的函数(get_object_functions),它接收一个对象(object_)作为它的参数,并返回一个包含对象类中定义的所有方法(包括静态方法和类方法)的列表(函数):

def get_object_functions(object_):
    functions = [attr_name
                 for attr_name in dir(object_)
                 if str(type(getattr(object_,
                                     attr_name))) in ("<class 'function'>",
                                                      "<class 'method'>")]
    return functions

好吧,它只是检查类的属性类型的字符串表示是否等于“<class 'function'>”或“<class 'method'>”,然后将该属性包含在函数列表中,如果那是True。


Demo

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f'My name is {self.name}')

    @staticmethod
    def say_hi():
        print('hi')

    @classmethod
    def reproduce(cls, name):
        return cls(name, 0)


person = Person('Rafael', 27)
print(get_object_functions(person))

输出

['__init__', 'introduce', 'reproduce', 'say_hi']

要获得更简洁的代码版本,请访问https://github.com/revliscano/utilities/blob/master/get_object_functions/object_functions_getter.py

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

help(object)

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

例如:

help(str)