如何在Python类中获取方法列表?

时间:2022-10-30 07:27:16

I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods?

我希望在类中遍历方法,或者根据当前的方法以不同的方式处理类或实例对象。如何获取类方法的列表?

Also see:

还看到:

8 个解决方案

#1


230  

An example (listing the methods of the optparse.OptionParser class):

一个示例(列出optparse的方法)。OptionParser类):

>>> from optparse import OptionParser
>>> import inspect
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
 ('add_option', <unbound method OptionParser.add_option>),
 ('add_option_group', <unbound method OptionParser.add_option_group>),
 ('add_options', <unbound method OptionParser.add_options>),
 ('check_values', <unbound method OptionParser.check_values>),
 ('destroy', <unbound method OptionParser.destroy>),
 ('disable_interspersed_args',
  <unbound method OptionParser.disable_interspersed_args>),
 ('enable_interspersed_args',
  <unbound method OptionParser.enable_interspersed_args>),
 ('error', <unbound method OptionParser.error>),
 ('exit', <unbound method OptionParser.exit>),
 ('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
 ...
 ]

Notice that getmembers returns a list of 2-tuples. The first item is the name of the member, the second item is the value.

注意,getmembers返回一个2元组的列表。第一项是成员的名称,第二项是值。

You can also pass an instance to getmembers:

您还可以将实例传递给getmembers:

>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...

#2


131  

There is the dir(theobject) method to list all the fields and methods of your object (as a tuple) and the inspect module (as codeape write) to list the fields and methods with their doc (in """).

有一个dir(theobject)方法来列出对象的所有字段和方法(如tuple)和检查模块(作为codeape写的),将字段和方法与他们的doc(在“”中)列出。

Because everything (even fields) might be called in Python, I'm not sure there is a built-in function to list only methods. You might want to try if the object you get through dir is callable or not.

因为在Python中,所有的东西(甚至字段)都可能被调用,所以我不确定是否有一个内置函数只列出方法。如果您通过dir的对象是可调用的,您可能想尝试一下。

#3


36  

Python 3.x answer without external libraries

Python 3。没有外部库的答案。

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]

dunder-excluded result:

dunder-excluded结果:

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]

#4


21  

Try the property __dict__.

房地产__dict__试试。

#5


10  

Note that you need to consider whether you want methods from base classes which are inherited (but not overridden) included in the result. The dir() and inspect.getmembers() operations do include base class methods, but use of the __dict__ attribute does not.

注意,您需要考虑是否需要从基础类中继承(但不重写)的方法。dir()和audit .getmembers()操作确实包含基类方法,但是使用__dict__属性则没有。

#6


10  

you can also import the FunctionType from types and test it with the class.__dict__:

您还可以从类型导入功能类型,并通过类.__dict__来测试它:

from types import FunctionType

class Foo:
    def bar(self): pass
    def baz(self): pass

def methods(cls):
    return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]

methods(Foo)  # ['bar', 'baz']

#7


0  

def find_defining_class(obj, meth_name):
    for ty in type(obj).mro():
        if meth_name in ty.__dict__:
            return ty

So

所以

print find_defining_class(car, 'speedometer') 

Think Python page 210

认为Python 210页

#8


-1  

I know this is an old post, but just wrote this function and will leave it here is case someone stumbles looking for an answer:

我知道这是一个旧的帖子,但写了这个功能,就会留下这是一个人在寻找答案时的错误:

def classMethods(the_class,class_only=False,instance_only=False,exclude_internal=True):

    def acceptMethod(tup):
        #internal function that analyzes the tuples returned by getmembers tup[1] is the 
        #actual member object
        is_method = inspect.ismethod(tup[1])
        if is_method:
            bound_to = tup[1].im_self
            internal = tup[1].im_func.func_name[:2] == '__' and tup[1].im_func.func_name[-2:] == '__'
            if internal and exclude_internal:
                include = False
            else:
                include = (bound_to == the_class and not instance_only) or (bound_to == None and not class_only)
        else:
            include = False
        return include
    #uses filter to return results according to internal function and arguments
    return filter(acceptMethod,inspect.getmembers(the_class))

#1


230  

An example (listing the methods of the optparse.OptionParser class):

一个示例(列出optparse的方法)。OptionParser类):

>>> from optparse import OptionParser
>>> import inspect
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
 ('add_option', <unbound method OptionParser.add_option>),
 ('add_option_group', <unbound method OptionParser.add_option_group>),
 ('add_options', <unbound method OptionParser.add_options>),
 ('check_values', <unbound method OptionParser.check_values>),
 ('destroy', <unbound method OptionParser.destroy>),
 ('disable_interspersed_args',
  <unbound method OptionParser.disable_interspersed_args>),
 ('enable_interspersed_args',
  <unbound method OptionParser.enable_interspersed_args>),
 ('error', <unbound method OptionParser.error>),
 ('exit', <unbound method OptionParser.exit>),
 ('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
 ...
 ]

Notice that getmembers returns a list of 2-tuples. The first item is the name of the member, the second item is the value.

注意,getmembers返回一个2元组的列表。第一项是成员的名称,第二项是值。

You can also pass an instance to getmembers:

您还可以将实例传递给getmembers:

>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...

#2


131  

There is the dir(theobject) method to list all the fields and methods of your object (as a tuple) and the inspect module (as codeape write) to list the fields and methods with their doc (in """).

有一个dir(theobject)方法来列出对象的所有字段和方法(如tuple)和检查模块(作为codeape写的),将字段和方法与他们的doc(在“”中)列出。

Because everything (even fields) might be called in Python, I'm not sure there is a built-in function to list only methods. You might want to try if the object you get through dir is callable or not.

因为在Python中,所有的东西(甚至字段)都可能被调用,所以我不确定是否有一个内置函数只列出方法。如果您通过dir的对象是可调用的,您可能想尝试一下。

#3


36  

Python 3.x answer without external libraries

Python 3。没有外部库的答案。

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]

dunder-excluded result:

dunder-excluded结果:

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]

#4


21  

Try the property __dict__.

房地产__dict__试试。

#5


10  

Note that you need to consider whether you want methods from base classes which are inherited (but not overridden) included in the result. The dir() and inspect.getmembers() operations do include base class methods, but use of the __dict__ attribute does not.

注意,您需要考虑是否需要从基础类中继承(但不重写)的方法。dir()和audit .getmembers()操作确实包含基类方法,但是使用__dict__属性则没有。

#6


10  

you can also import the FunctionType from types and test it with the class.__dict__:

您还可以从类型导入功能类型,并通过类.__dict__来测试它:

from types import FunctionType

class Foo:
    def bar(self): pass
    def baz(self): pass

def methods(cls):
    return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]

methods(Foo)  # ['bar', 'baz']

#7


0  

def find_defining_class(obj, meth_name):
    for ty in type(obj).mro():
        if meth_name in ty.__dict__:
            return ty

So

所以

print find_defining_class(car, 'speedometer') 

Think Python page 210

认为Python 210页

#8


-1  

I know this is an old post, but just wrote this function and will leave it here is case someone stumbles looking for an answer:

我知道这是一个旧的帖子,但写了这个功能,就会留下这是一个人在寻找答案时的错误:

def classMethods(the_class,class_only=False,instance_only=False,exclude_internal=True):

    def acceptMethod(tup):
        #internal function that analyzes the tuples returned by getmembers tup[1] is the 
        #actual member object
        is_method = inspect.ismethod(tup[1])
        if is_method:
            bound_to = tup[1].im_self
            internal = tup[1].im_func.func_name[:2] == '__' and tup[1].im_func.func_name[-2:] == '__'
            if internal and exclude_internal:
                include = False
            else:
                include = (bound_to == the_class and not instance_only) or (bound_to == None and not class_only)
        else:
            include = False
        return include
    #uses filter to return results according to internal function and arguments
    return filter(acceptMethod,inspect.getmembers(the_class))