我想遍历类中的方法,或者根据现有方法以不同的方式处理类或实例对象。如何获得类方法列表?
还看到:
如何列出a中的方法Python 2.5模块?循环在Python / IronPython对象方法找到方法和对象有我怎么看里面Python对象?我怎么对in中的对象执行内省Python 2. x ?如何获得对象的方法和的完整列表属性?发现这函数可以从类中获得在python中实例?一个例子(列出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | >>> 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>), ... ] |
注意,
你也可以传递一个实例给
1 2 3 | >>> parser = OptionParser() >>> inspect.getmembers(parser, predicate=inspect.ismethod) ... |
有
因为所有东西(甚至字段)都可能在Python中调用,所以我不确定是否有一个内置函数只列出方法。您可能想尝试通过
Python 3。x答案没有外部库
1 | method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))] |
dunder-excluded结果:
1 | method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")] |
尝试属性
您还可以从类型中导入FunctionType并用
1 2 3 4 5 6 7 8 9 10 | 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'] |
注意,您需要考虑是否希望在结果中包含继承(但不重写)基类中的方法。
假设您想知道与list类关联的所有方法只需输入以下内容
1 | print (dir(list)) |
上面将给出list类的所有方法
1 2 3 4 | def find_defining_class(obj, meth_name): for ty in type(obj).mro(): if meth_name in ty.__dict__: return ty |
所以
1 | print find_defining_class(car, 'speedometer') |
想想Python第210页
如果只想列出python类的方法
1 2 | import numpy as np print(np.random.__all__) |
这同样适用:
mymodule.py
1 2 3 4 | def foo(x) return 'foo' def bar() return 'bar' |
在另一个文件
1 2 3 | import inspect import mymodule method_list = [ func[0] for func in inspect.getmembers(mymodule, predicate=inspect.isroutine) if callable(getattr(mymodule, func[0])) ] |
输出:
1 | ['foo', 'bar'] |
来自python文档:
inspect.isroutine(对象)
1 | Return true if the object is a user-defined or built-in function or method. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class CPerson: def __init__(self, age): self._age = age def run(self): pass @property def age(self): return self._age @staticmethod def my_static_method(): print("Life is short, you need Python") @classmethod def say(cls, msg): return msg test_class = CPerson # print(dir(test_class)) # list all the fields and methods of your object print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ == 'function' and not name.startswith('__')]) print([(name, t) for name, t in test_class.__dict__.items() if type(t).__name__ != 'function' and not name.startswith('__')]) |
输出
1 2 | [('run', <function CPerson.run at 0x0000000002AD3268>)] [('age', <property object at 0x0000000002368688>), ('my_static_method', <staticmethod object at 0x0000000002ACBD68>), ('say', <classmethod object at 0x0000000002ACF0B8>)] |
如果您的方法是"常规"方法,而不是
for k, v in your_class.__dict__.items():
if"function" in str(v):
print(k)
这可以通过相应地改变
我知道这是一个旧的帖子,但只是写了这个函数,并将它留在这里,以防有人在寻找答案时出错:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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)) |