pythonclassmethods

How do I get the methods (with parameters) of a Python class while keeping the original order of the methods?


The dir() function prints the methods in alphabetical order. Is there a way to get the methods of a class (with their parameters) but keeping the original order of the methods?

Here's my code

return [
    (m, getattr(PythonClass, m).__code__.co_varnames)
    for m in dir(PythonClass)
]

Solution

  • As @Barmar mentioned in the comments, you can use the __dict__ attribute of a class to access its attributes. Since Python 3.7 dict keys are guaranteed to retain their insertion order, so by iterating over PythonClass.__dict__ you can obtain attributes of PythonClass in the order of definition. It is also more idiomatic to use the vars function instead of the __dict__ attribute to access the attributes dict. To filter class attributes for methods, you can use inspect.isfunction to test if an attribute is a function:

    from inspect import isfunction
    
    class PythonClass:
        var = 1
        def method_b(self, b): ...
        def method_a(self, a): ...
    
    print([
        (name, obj.__code__.co_varnames)
        for name, obj in vars(PythonClass).items() if isfunction(obj)
    ])
    

    This outputs:

    [('method_b', ('self', 'b')), ('method_a', ('self', 'a'))]
    

    Demo: https://ideone.com/rNMcYO