如何获取 Python 类中的方法列表? [英] How do I get list of methods in a Python class?
本文介绍了如何获取 Python 类中的方法列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想遍历类中的方法,或者根据存在的方法以不同方式处理类或实例对象.如何获取类方法列表?
另见:
- 如何列出中的方法Python 2.5 模块?
- 循环一个 Python/IronPython 对象方法
- 找到方法对象有
- 如何查看内部一个 Python 对象?
- 我该怎么做对对象执行自省Python 2.x?
- 如何获得对象方法的完整列表和属性?
- 找出哪个函数可从类中获得python中的实例?
解决方案
一个例子(列出了 optparse.OptionParser
类的方法):
注意 getmembers
返回一个 2 元组列表.第一项是成员的名称,第二项是值.
您还可以将实例传递给 getmembers
:
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:
- How can I list the methods in a Python 2.5 module?
- Looping over a Python / IronPython Object Methods
- Finding the methods an object has
- How do I look inside a Python object?
- How Do I Perform Introspection on an Object in Python 2.x?
- How to get a complete list of object’s methods and attributes?
- Finding out which functions are available from a class instance in python?
解决方案
An example (listing the methods of the optparse.OptionParser
class):
>>> from optparse import OptionParser
>>> import inspect
#python2
>>> 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>),
...
]
# python3
>>> inspect.getmembers(OptionParser, predicate=inspect.isfunction)
...
Notice that getmembers
returns a list of 2-tuples. The first item is the name of the member, the second item is the value.
You can also pass an instance to getmembers
:
>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...
这篇关于如何获取 Python 类中的方法列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文