查找Python对象具有哪些方法

680

给定任何类型的Python对象,是否有一种简单的方法可以获取此对象拥有的所有方法列表?

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


相关:https://dev59.com/NaTja4cB1Zd3GeqPIuFD - 0 _
22个回答

753

对于许多对象,您可以使用此代码,将“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'])

6
这是一个列表推导式,返回一个方法列表,其中每个方法都是由dir(object)返回的列表中的一个项,并且只有在getattr(object, method)返回可调用对象时才将每个方法添加到列表中。 - Mnebuerquo
17
打印对象的方法:print [method for method in dir(object) if callable(getattr(object, method))] - Orienteerix
2
当我尝试运行这个程序时,出现了AttributeError: module 'pandas.core.common' has no attribute 'AbstractMethodError'错误。请参见https://dev59.com/ebHma4cB1Zd3GeqPSeIE获取详细信息。 - Karl Baker
排除双下划线方法:[ m for m in dir(object) if not m.startswith('__')] - John
另一种使用过滤器的方法:print(list(filter(lambda x: x[0] != '_' and callable(getattr(obj, x)), dir(obj)))) - Paulo Buchsbaum
尽管这种情况并不常见,但它将返回可调用的实例属性而不是方法。方法是通过从实例中调用class属性来产生的。此外,dir不能可靠地获取对象的所有属性;最重要的是,一个类可以通过覆盖__dir__来定义dir返回的内容。 - chepner

364

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

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

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

有关更多信息,请参见Python内省


2
“Guide to Python Introspection”这个链接似乎已经失效了。 - Love and peace - Joe Codeswell
2
@Loveandpeace-JoeCodeswell 谢谢。我找不到原始资源,所以我不得不用另一篇文章的链接来更新它。 - Bill the Lizard

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

6
它还显示了对象的属性,所以如果你想找到特定的方法,它就不起作用了。 - eric
是的。同意。但是,我不知道任何其他技术只获取方法列表。也许最好的想法是获取属性和方法的列表,然后使用<hasattr(object,“method_name”>进一步过滤它? - Pawan Kumar
2
@neuronet,我正在尝试运行被接受的答案,但是出现了“AttributeError: module 'pandas.core.common' has no attribute 'AbstractMethodError'”错误。有什么想法吗?请参见 https://dev59.com/ebHma4cB1Zd3GeqPSeIE 获取详细信息。+1 给 @Pawan Kumar,因为他的答案有效,以及给 @ljs,因为他承诺提供一个仅包含方法的过滤列表。 - Karl Baker

41

我认为你想要类似这样的内容:

从一个对象中列出属性列表

内置函数dir()可以完成这个任务。

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

dir(...)

dir([object]) -> list of strings

如果没有参数调用,则返回当前作用域中的名称。

否则,返回给定对象的(一些)属性及其可达属性组成的按字母排序的名称列表。

如果对象提供了名为__dir__的方法,则使用它;否则使用默认的dir()逻辑,并返回:

  • 对于模块对象:模块的属性。
  • 对于类对象:其属性以及递归其基类的属性。
  • 对于任何其他对象:其属性、其类的属性以及递归其类的基类的属性。

例如:

$ 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']

35

检查它是否具有特定的方法:

hasattr(object,"method")

16
因为提问者正在寻找方法而不仅仅是属性,所以我认为你需要更进一步,使用以下代码:if hasattr(obj, method) and callable(getattr(obj, method)): - Bruno Bronosky

29

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

help(object)
它会列出与该对象相关的所有可用或重要方法。 例如:
help(str)

28

除了更直接的答案外,我还要提到IPython

按下Tab键可以查看可用的方法并进行自动完成。一旦找到方法,请尝试:

help(object.method)

查看Python文档、方法签名等内容。

啊...REPL


25

假设我们有一个Python obj。为了查看它具有的所有方法,包括那些被__magic methods)包围的方法:

print(dir(obj))

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

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

21
如果您特别想要 方法,您应该使用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)]
有时候inspect.isroutine也很有用(对于内置函数、C扩展、没有“binding”编译指令的Cython)。

2
你应该使用 inspect.getmembers 而不是在列表推导式中使用 dir,这样更好。 - user3064538
2
inspect.getmembers(self, predicate=inspect.ismethod) ? 检查 self 对象的成员,谓词为 inspect.ismethod - hwjp

16

打开Bash shell(在Ubuntu上按Ctrl + Alt + T)。在其中启动Python 3 shell。创建一个要观察方法的对象。只需在其后加上一个点并按两次Tab,您将看到类似以下内容:

user@note:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> s = "Any object. Now it's a string"
>>> s. # here tab should be pressed twice
s.__add__(           s.__rmod__(          s.istitle(
s.__class__(         s.__rmul__(          s.isupper(
s.__contains__(      s.__setattr__(       s.join(
s.__delattr__(       s.__sizeof__(        s.ljust(
s.__dir__(           s.__str__(           s.lower(
s.__doc__            s.__subclasshook__(  s.lstrip(
s.__eq__(            s.capitalize(        s.maketrans(
s.__format__(        s.casefold(          s.partition(
s.__ge__(            s.center(            s.replace(
s.__getattribute__(  s.count(             s.rfind(
s.__getitem__(       s.encode(            s.rindex(
s.__getnewargs__(    s.endswith(          s.rjust(
s.__gt__(            s.expandtabs(        s.rpartition(
s.__hash__(          s.find(              s.rsplit(
s.__init__(          s.format(            s.rstrip(
s.__iter__(          s.format_map(        s.split(
s.__le__(            s.index(             s.splitlines(
s.__len__(           s.isalnum(           s.startswith(
s.__lt__(            s.isalpha(           s.strip(
s.__mod__(           s.isdecimal(         s.swapcase(
s.__mul__(           s.isdigit(           s.title(
s.__ne__(            s.isidentifier(      s.translate(
s.__new__(           s.islower(           s.upper(
s.__reduce__(        s.isnumeric(         s.zfill(
s.__reduce_ex__(     s.isprintable(
s.__repr__(          s.isspace(

2
当我们谈论这样的解决方法时,我会补充说,您也可以运行 ipython,开始键入对象并按 tab 键,它也可以工作。无需 readline 设置。 - Max Coplan
2
@MaxCoplan,我已经在代码中添加了解决方法,以处理默认情况下未启用制表符补全的情况。 - Valery Ramusik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接