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

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


当前回答

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

这应该工作:)

其他回答

以便在整个模块中搜索特定的方法

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

以列表为对象

obj = []

list (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']

我已经完成了下面的函数(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

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

检查方法是否存在可以通过callable(getattr(object, method))来完成,就像前面提到的那样。

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

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

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

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