查找 Python 对象有哪些方法

发布于 2024-07-04 02:57:29 字数 119 浏览 6 评论 0 原文

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

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

Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?

Or if this is not possible, is there at least an easy way to check if it has a particular method, other than checking if an error occurs when the method is called?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(22

盗梦空间 2024-07-11 02:57:30

可以创建一个 getAttrs 函数,该函数将返回对象的可调用属性

def getAttrs(object):
  return filter(lambda m: callable(getattr(object, m)), dir(object))

print getAttrs('Foo bar'.split(' '))

名称

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
 '__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__', 
 '__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__', 
 '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', 
 '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', 
 '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', 
 '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 
 'remove', 'reverse', 'sort']

One can create a getAttrs function that will return an object's callable property names

def getAttrs(object):
  return filter(lambda m: callable(getattr(object, m)), dir(object))

print getAttrs('Foo bar'.split(' '))

That'd return

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
 '__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__', 
 '__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__', 
 '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', 
 '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', 
 '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', 
 '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 
 'remove', 'reverse', 'sort']
¢蛋碎的人ぎ生 2024-07-11 02:57:30

将列表作为对象

obj = []

list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))

你会得到:

['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

Take a list as an object

obj = []

list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))

You get:

['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']
心房的律动 2024-07-11 02:57:30

为了在整个模块中搜索特定方法

for method in dir(module) :
  if "keyword_of_methode" in method :
   print(method, end="\n")

In order to search for a specific method in a whole module

for method in dir(module) :
  if "keyword_of_methode" in method :
   print(method, end="\n")
眉黛浅 2024-07-11 02:57:30

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

While "请求宽恕比请求许可更容易" 肯定是 Pythonic 方式,您可能正在寻找:

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

...is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called

While "Easier to ask for forgiveness than permission" is certainly the Pythonic way, you may be looking for:

d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
    d.get('foo')
# OUT: 'bar'
思慕 2024-07-11 02:57:30

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

import module_name
dir(module_name)

您还可以将对象传递给 dir() 作为

dir(object_name)

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

You can make use of dir() which is pre-defined in Python.

import module_name
dir(module_name)

You can also pass an object to dir() as

dir(object_name)

If the object is an object of a pre-defined class such as int, str, etc. it displays the methods in it (you may know those methods as built in functions). If that object is created for a user-defined class, it displays all the methods given in that class.

谁对谁错谁最难过 2024-07-11 02:57:30

例如,如果您使用 shell plus,则可以使用它:

>> MyObject??

这样,使用 '??' 在您的对象之后,它将显示该类具有的所有属性/方法。

If you are, for instance, using shell plus you can use this instead:

>> MyObject??

that way, with the '??' just after your object, it'll show you all the attributes/methods the class has.

风蛊 2024-07-11 02:57:30

这是一个很好的单行(但也会获得属性):

print(*dir(obj), sep='\n')

Here's a nice one liner (but will get attributes as well):

print(*dir(obj), sep='\n')
勿挽旧人 2024-07-11 02:57:30

大多数时候,我想看到用户定义的方法,而不想看到以'__'开头的内置属性,如果您愿意,可以使用以下代码:

object_methods = [method_name for method_name in dir(object) if callable(getattr(object, method_name)) and '__' not in method_name] 

例如,对于这个类:

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

上面的代码将打印:['print_name']

Most of the time, I want to see the user-defined methods and I don't want to see the built-in attributes that start with '__', if you want that you can use the following code:

object_methods = [method_name for method_name in dir(object) if callable(getattr(object, method_name)) and '__' not in method_name] 

For example, for this class:

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

Above code will print: ['print_name']

终止放荡 2024-07-11 02:57:30

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

help(object)

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

例如:

help(str)

The simplest way to get a list of methods of any object is to use the help() command.

help(object)

It will list out all the available/important methods associated with that object.

For example:

help(str)
请恋爱 2024-07-11 02:57:30

除了更直接的答案之外,如果我没有提到IPython,那就是我的失职。

点击 Tab 查看可用的方法,并带有自动完成功能。

一旦找到方法,请尝试:

help(object.method)

查看 pydocs、方法签名等。

啊... REPL

On top of the more direct answers, I'd be remiss if I didn't mention IPython.

Hit Tab to see the available methods, with autocompletion.

And once you've found a method, try:

help(object.method)

to see the pydocs, method signature, etc.

Ahh... REPL.

感情旳空白 2024-07-11 02:57:30

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

hasattr(object,"method")

To check if it has a particular method:

hasattr(object,"method")
苍白女子 2024-07-11 02:57:30

如果您特别想要方法,则应该使用inspect .is方法

对于方法名称:

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< /code> 也很有用(对于内置函数、C 扩展、没有“绑定”编译器指令的 Cython)。

If you specifically want methods, you should use inspect.ismethod.

For method names:

import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]

For the methods themselves:

import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]

Sometimes inspect.isroutine can be useful too (for built-ins, C extensions, Cython without the "binding" compiler directive).

沫尐诺 2024-07-11 02:57:30

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

print(dir(obj))

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

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

Suppose we have a Python obj. Then to see all the methods it has, including those surrounded by __ (magic methods):

print(dir(obj))

To exclude magic builtins one would do:

[m for m in dir(obj) if not m.startswith('__')]
眼泪淡了忧伤 2024-07-11 02:57:30
import moduleName
for x in dir(moduleName):
    print(x)

这应该有效:)

import moduleName
for x in dir(moduleName):
    print(x)

This should work :)

绿光 2024-07-11 02:57:30

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

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

There is no reliable way to list all object's methods. dir(object) is usually useful, but in some cases it may not list all methods. According to dir() documentation: "With an argument, attempt to return a list of valid attributes for that object."

Checking that method exists can be done by callable(getattr(object, method)) as already mentioned there.

我只土不豪 2024-07-11 02:57:30

此处指出的所有方法的问题是您无法确定某个方法不存在。

在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 中的宽恕优于许可 范例。

The problem with all methods indicated here is that you can't be sure that a method doesn't exist.

In Python you can intercept the dot calling through __getattr__ and __getattribute__, making it possible to create method "at runtime"

Example:

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

If you execute it, you can call non-existing methods in the object dictionary...

>>> 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

And it's why you use the Easier to ask for forgiveness than permission paradigms in Python.

菩提树下叶撕阳。 2024-07-11 02:57:30

打开 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(

Open a Bash shell (Ctrl + Alt + T on Ubuntu). Start a Python 3 shell in it. Create an object to observe the methods of. Just add a dot after it and press Tab twice and you'll see something like this:

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(
夜清冷一曲。 2024-07-11 02:57:30

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

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

嗯,它只是检查类属性类型的字符串表示形式是否等于 """",然后将该属性包含在 functions 列表中(如果该属性为 True< /代码>。


演示

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

I have done the following function (get_object_functions), which receives an object (object_) as its argument, and returns a list (functions) containing all of the methods (including static and class methods) defined in the object's class:

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

Well, it just checks if the string representation of the type of a class' attribute equals "<class 'function'>" or "<class 'method'>" and then includes that attribute in the functions list if that's 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))

Output

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

For a cleaner version of the code: https://github.com/revliscano/utilities/blob/master/get_object_functions/object_functions_getter.py

一腔孤↑勇 2024-07-11 02:57:29

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

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

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

有关详细信息,请参阅 Python 内省

You can use the built in dir() function to get a list of all the attributes a module has. Try this at the command line to see how it works.

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

Also, you can use the hasattr(module_name, "attr_name") function to find out if a module has a specific attribute.

See the Python introspection for more information.

酒中人 2024-07-11 02:57:29

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

The simplest method is to use dir(objectname). It will display all the methods available for that object.

記憶穿過時間隧道 2024-07-11 02:57:29

我相信你想要这样的东西:

对象的属性列表

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

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

目录(...)

dir([object]) ->;   字符串列表 
  

如果不带参数调用,则返回当前范围内的名称。

否则,返回按字母顺序排列的名称列表,其中包含给定对象的(部分)属性以及可从该对象访问的属性。

如果对象提供了名为__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']

I believe that you want something like this:

a list of attributes from an object

The built-in function dir() can do this job.

Taken from help(dir) output on your Python shell:

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.

For example:

$ 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']
佼人 2024-07-11 02:57:29

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

For many objects, you can use this code, replacing 'object' with the object you're interested in:

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

I discovered it at diveintopython.net (now archived), that should provide some further details!

If you get an AttributeError, you can use this instead:

getattr() is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions.

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'])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文