查找Python对象具有的方法

Tho*_*zer 379 python introspection

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

要么,

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

ljs*_*ljs 475

您似乎可以使用此代码,将"对象"替换为您感兴趣的对象:

object_methods = [method_name for method_name in dir(object)
                  if callable(getattr(object, method_name))]
Run Code Online (Sandbox Code Playgroud)

我在这个网站上发现了它.希望,这应该提供一些进一步的细节!

  • @marsh打印方法:`print [dir(object)中方法的方法,如果可调用(getattr(object,method))]`. (12认同)
  • 这是一个列表解析,返回一个方法列表,其中method是dir(object)返回的列表中的项,并且只有当getattr(object,method)返回callable时,每个方法才会添加到列表中. (2认同)
  • 当我尝试运行此命令时,出现“AttributeError: module 'pandas.core.common' has no attribute 'AbstractMethodError'”。详情请参阅 /sf/ask/3829930121/。 (2认同)

Bil*_*ard 201

您可以使用内置dir()函数来获取模块具有的所有属性的列表.在命令行中尝试此操作以查看其工作原理.

>>> import moduleName
>>> dir(moduleName)
Run Code Online (Sandbox Code Playgroud)

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

有关更多信息,请参阅Python内省指南.

  • “Python 内省指南”链接似乎已失效。 (2认同)
  • @Loveandpeace-JoeCodeswell 谢谢。我找不到原始资源,因此我必须使用指向另一篇文章的链接来更新它。 (2认同)

Paw*_*mar 77

最简单的方法是使用dir(objectname).它将显示该对象可用的所有方法.很酷的把戏.

  • 它还显示了对象的属性,所以如果要专门查找方法,它是行不通的。 (4认同)
  • @neuronet,我正在尝试运行已接受的答案,但收到“AttributeError: module 'pandas.core.common' has no attribute 'AbstractMethodError'”。有任何想法吗?请参阅 /sf/ask/3829930121/ 上的详细信息。+1 给@Pawan Kumar b/c,答案有效,并给@ljs 承诺仅包含方法的过滤列表。 (2认同)

小智 31

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

hasattr(object,"method")
Run Code Online (Sandbox Code Playgroud)

  • 由于OP正在寻找一种方法而不仅仅是属性,我想你想更进一步:`if hasattr(obj,method)和callable(getattr(obj,method)):` (13认同)

iva*_*ncz 27

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

来自对象的属性列表

在我看来,内置函数dir()可以为您完成这项工作.取自help(dir)Python Shell上的输出:

目录(...)

dir([object]) -> list of strings
Run Code Online (Sandbox Code Playgroud)

如果在没有参数的情况下调用,则返回当前范围中的名称.

否则,返回一个按字母顺序排列的名称列表,其中包含给定对象的(某些)属性以及可从中获取的属性.

如果对象提供了一个名为的方法__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']
Run Code Online (Sandbox Code Playgroud)

当我检查你的问题时,我决定展示我的思路,更好地格式化输出dir().

dir_attributes.py(Python 2.7.6)

#!/usr/bin/python
""" Demonstrates the usage of dir(), with better output. """

__author__ = "ivanleoncz"

obj = "I am a string."
count = 0

print "\nObject Data: %s" % obj
print "Object Type: %s\n" % type(obj)

for method in dir(obj):
    # the comma at the end of the print, makes it printing 
    # in the same line, 4 times (count)
    print "| {0: <20}".format(method),
    count += 1
    if count == 4:
        count = 0
        print
Run Code Online (Sandbox Code Playgroud)

dir_attributes.py(Python 3.4.3)

#!/usr/bin/python3
""" Demonstrates the usage of dir(), with better output. """

__author__ = "ivanleoncz"

obj = "I am a string."
count = 0

print("\nObject Data: ", obj)
print("Object Type: ", type(obj),"\n")

for method in dir(obj):
    # the end=" " at the end of the print statement, 
    # makes it printing in the same line, 4 times (count)
    print("|    {:20}".format(method), end=" ")
    count += 1
    if count == 4:
        count = 0
        print("")
Run Code Online (Sandbox Code Playgroud)

希望我贡献:).


jma*_*g2k 23

除了更直接的答案之外,如果我没有提及iPython,我将会失职.点击"标签"以查看可用的方法,并使用自动完成功能.

一旦找到方法,请尝试:

help(object.method) 
Run Code Online (Sandbox Code Playgroud)

查看pydocs,方法签名等

啊...... REPL.


Ser*_*nov 13

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

print(dir(obj))
Run Code Online (Sandbox Code Playgroud)

要仅查看通过中缀(点)表示法可用的方法,可以:

[m for m in dir(obj) if not m.startswith('__')]
Run Code Online (Sandbox Code Playgroud)


pau*_*kow 12

如果您特别需要方法,则应使用inspect.ismethod.

对于方法名称:

import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]
Run Code Online (Sandbox Code Playgroud)

对于方法本身:

import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]
Run Code Online (Sandbox Code Playgroud)

有时候inspect.isroutine也很有用(对于内置插件,C扩展,没有"绑定"编译器指令的Cython).

  • 难道你不应该在列表理解中使用 [`inspect.getmembers`](https://docs.python.org/3/library/inspect.html#inspect.getmembers) 而不是使用 `dir` 吗? (2认同)
  • `inspect.getmembers(self, predicate=inspect.ismmethod)` ? (2认同)

Val*_*sik 11

打开bash shell(在Ubuntu上按ctrl + alt + T).在其中启动python3 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(           
Run Code Online (Sandbox Code Playgroud)

  • 当我们讨论这样的解决方法时,我会补充一点,您还可以运行“ipython”,开始输入对象并按“tab”,它也会起作用。无需读取行设置 (2认同)
  • @MaxCoplan我已经在代码中添加了针对默认情况下未启用制表符完成功能的情况的解决方法 (2认同)

小智 7

这里指出的所有方法的问题是您不能确定方法不存在.

在Python可以拦截点主叫通__getattr____getattribute__,从而能够创建方法"在运行时"

例:

class MoreMethod(object):
    def some_method(self, x):
        return x
    def __getattr__(self, *args):
        return lambda x: x*2
Run Code Online (Sandbox Code Playgroud)

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

>>> 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
Run Code Online (Sandbox Code Playgroud)

这就是为什么你使用Easier来请求宽恕而不是 Python中的权限范例.


小智 6

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

%help(object)
Run Code Online (Sandbox Code Playgroud)

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

例如:

help(str)
Run Code Online (Sandbox Code Playgroud)


ave*_*ver 5

没有可靠的方法来列出所有对象的方法。dir(object)通常很有用,但在某些情况下它可能不会列出所有方法。根据dir()文档“使用参数,尝试返回该对象的有效属性列表。”

callable(getattr(object, method))检查方法是否存在可以通过已经提到的方法来完成。