按照代码中的顺序获取类的方法

san*_*82h 6 python members inspect

这段代码:

import inspect

class Obj():

    def c(self):
        return 1

    def b(self):
        return 2

    def a(self):
        return 3

o = Obj()

for name, value in inspect.getmembers(o, inspect.ismethod):
    print str(value())+" "+name
Run Code Online (Sandbox Code Playgroud)

打印:

3 a
2 b
1 c
Run Code Online (Sandbox Code Playgroud)

因为inspect.getmembers返回按名称排序的(名称,值)对列表中对象的所有成员,您可以在https://docs.python.org/2/library/inspect.html#inspect.getmembers中阅读

但我想按照成员在代码中编写的顺序获取该列表,换句话说,输出将是:

1 c
2 b
3 a
Run Code Online (Sandbox Code Playgroud)

有办法做到这一点吗?

谢谢

jua*_*aga 1

嗯,这非常 hacky,但基本上我直接检查源代码并用于re查找方法名称。不过,这个解决方案非常脆弱,而且它不处理继承,但也许它对你有用。假设我已将您的类定义保存在名为的文件中test.py

>>> import test
>>> import re
>>> findmethods = re.compile(r"    def (.+)\(")
>>> findmethods.findall(inspect.getsource(test.Obj))
['c', 'b', 'a']
>>>
Run Code Online (Sandbox Code Playgroud)