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

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


当前回答

您可以使用内置的dir()函数来获得模块的所有属性的列表。在命令行上尝试一下,看看它是如何工作的。

>>> import moduleName
>>> dir(moduleName)

另外,您可以使用hasattr(module_name, "attr_name")函数来确定模块是否具有特定的属性。

有关更多信息,请参阅Python自省。

其他回答

我相信你想要的是这样的:

一个对象的属性列表

内置函数dir()可以完成这项工作。

摘自Python shell的help(dir)输出:

dir(...) dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns: for a module object: the module's attributes. for a class object: its attributes, and recursively the attributes of its bases. for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes.

例如:

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> a = "I am a string"
>>>
>>> type(a)
<class 'str'>
>>>
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'_formatter_field_name_split', '_formatter_parser', 'capitalize',
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']

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

在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中使用“请求原谅比请求许可更容易”的范例。

对于许多对象,你可以使用这段代码,用你感兴趣的对象替换'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中预定义的dir()。

import module_name
dir(module_name)

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

dir(object_name)

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

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

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

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

help(object.method)

查看pydocs、方法签名等。

啊…REPL。