我想遍历类中的方法,或根据存在的方法以不同方式处理类或实例对象。如何获取类方法列表?
另请参见:
我想遍历类中的方法,或根据存在的方法以不同方式处理类或实例对象。如何获取类方法列表?
另请参见:
一个例子(列出optparse.OptionParser
类的方法):
>>> 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)
...
请注意getmembers
返回一个由2元组组成的列表,第一个元素是成员的名称,第二个元素是其值。
你也可以将实例传递给getmembers
:
>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...
有一个dir(theobject)
方法可以列出您的对象的所有字段和方法(作为元组),还有inspect模块(如codeape所写)可以列出带有其文档的字段和方法(在""中)。
因为在Python中可以调用任何东西(甚至是字段),我不确定是否有内置函数仅列出方法。您可能需要尝试通过dir
获取的对象是否callable。
不使用外部库的Python 3.x答案
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
dunder-excluded结果:
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]
@property
和@property.setter
修饰的getter-setter方法。 - leonard vertighel假设你想知道与列表类相关联的所有方法,请键入以下命令
print (dir(list))
以上将为您提供所有列表类的方法
print([ m for m in dir(my_class) if not m.startswith('__')])
- Evhz尝试使用属性 __dict__
。
__dict__
。然而,类也有一个__dict__
,应该显示类方法 :) - Seaux你还可以从types模块导入FunctionType,并使用class.__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']
and not x.startswith('_')
,以便忽略 __init__
和私有方法。 - Christopher Pearsontype()
来摆脱FunctionType
的导入:type(lambda:0)
- Tersosaurosisinstance
比type(y) == FunctionType
更好。 - Gloweyex
替换为 y
(使用 [y for x, y in cls.__dict__.items() if type(y) == FunctionType]
)。 - matan hdir(className)
这将返回类中所有方法名称的列表。请注意,您需要考虑是否希望将继承的(但未被覆盖)基类方法包含在结果中。 dir()
和inspect.getmembers()
操作确实包括基类方法,但使用__dict__
属性则不包括。
staticmethod
、classmethod
等for k, v in your_class.__dict__.items():
if "function" in str(v):
print(k)
if
条件中来扩展到其他类型的方法。types.FunctionTypes
判断变量 v
是否为函数类型会更简洁。你还可以扩展这个方法来检查是否为 classmethod
和 staticmethod
类型的属性。 - chepnerif isinstance(v, types.FunctionType)
。 - srgsanky尝试使用 print(help(类名))
命令,可以打印出该类的方法。
staticmethod
:我想知道是否可能。 - mike rodent
inspect.isroutine
可能是更合适的谓词;inspect.ismethod
不适用于所有对象的方法。 - Gavin S. YanceyOptionsParser
类的所有函数成员:inspect.getmembers(OptionsParser, predicate=inspect.isfunction)
。 - codeape