2024-04-26 21:02:39 发布
网友
我想遍历类中的方法,或者根据现有方法以不同的方式处理类或实例对象。如何获取类方法列表?
另见:
示例(列出optparse.OptionParser类的方法):
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>), ... ]
注意,getmembers返回一个2元组的列表。第一项是成员的名称,第二项是值。
getmembers
您还可以将实例传递给getmembers:
>>> parser = OptionParser() >>> inspect.getmembers(parser, predicate=inspect.ismethod) ...
不带外部库的Python3.x应答
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
邓德排除结果:
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]
有一个dir(theobject)方法列出对象的所有字段和方法(作为元组),而inspect模块(作为codeape write)列出字段和方法及其doc(in“”)。
dir(theobject)
因为所有内容(甚至字段)都可能在Python中调用,所以我不确定是否有一个内置函数只列出方法。如果您通过的对象是dir或不是callable,您可能想试试。
dir
示例(列出
optparse.OptionParser
类的方法):注意,
getmembers
返回一个2元组的列表。第一项是成员的名称,第二项是值。您还可以将实例传递给
getmembers
:不带外部库的Python3.x应答
邓德排除结果:
有一个
dir(theobject)
方法列出对象的所有字段和方法(作为元组),而inspect模块(作为codeape write)列出字段和方法及其doc(in“”)。因为所有内容(甚至字段)都可能在Python中调用,所以我不确定是否有一个内置函数只列出方法。如果您通过的对象是
dir
或不是callable,您可能想试试。相关问题 更多 >
编程相关推荐