No. Class members are not ordered. They are gathered into a dictionary, immediately losing order. You can resort to tricks like parsing the source, but it will break easily. For starters, the source could not be available.
[edit: it seems python3 allows more flexibility in class creation, making it possible to customize the way class members are gathered, if you are on python3 only, that's probably a better approach]
If changing the code is not a problem, you can use a decorator though:
import inspect
def track_order(fn):
fn.order = track_order.idx
track_order.idx += 1
return fn
track_order.idx = 0
class Obj(object):
@track_order
def c(self):
return 1
@track_order
def b(self):
return 2
@track_order
def a(self):
return 3
o = Obj()
methods = sorted((item
for item in inspect.getmembers(o, inspect.ismethod)),
key=lambda item: item[1].order)
for name, value in methods:
print str(value())+" "+name
The decorator adds an idx attribute to all methods that pass through it.
This makes use of the fact that python has first-class functions.
$ python test.py
1 c
2 b
3 a
Note: this is the method used by Django to keep track of form and model fields order. Only, they don't need a decorator because fields' classes have the instanciation order attribute built-in (it is named creation_counter).