How do I list only the methods I define in a class?

bruceg113355 at gmail.com bruceg113355 at gmail.com
Fri Jun 1 09:28:45 EDT 2018


On Thursday, May 31, 2018 at 10:18:53 PM UTC-4, bob gailer wrote:
> On 5/31/2018 3:49 PM, bruceg113355 at gmail.com wrote:
>  > How do I list only the methods I define in a class?
> Here's a class with some method, defined in various ways:
> 
>  >>> class x():
> ...     a=3
> ...     def f():pass
> ...     g = lambda: None
> ...
> 
>  >>> l=[v for v in x.__dict__.items()]; print(l)
> [('a', 3), ('f', <function x.f at 0x000001DEDD693840>), ('__module__', 
> '__main__'), ('__dict__', <attribute '__dict__' of 'x' objects>), 
> ('__doc__', None), ('__weakref__', <attribute '__weakref__' of 'x' 
> objects>)]
> 
>  >>> import inspect
>  >>> [(key, value) for key, value in l if inspect.isfunction(i[1])]
> [('f', <function x.f at 0x000001DEDD6936A8>), ('g', <function x.<lambda> 
> at 0x000001DEDD693620>)]
> 
> HTH




After more researching, I found the below code that works for me.

https://stackoverflow.com/questions/1911281/how-do-i-get-list-of-methods-in-a-python-class


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]


Using the above code, I now get the following.
    ['__init__', 'apples', 'peaches', 'pumpkin']

Bruce




More information about the Python-list mailing list