Find all instance members in python excluding __init__

the vars keyword gives me all the variables in the instance, for example:

 In [245]: vars(a) Out[245]: {'propa': 0, 'propb': 1} 

However, I don’t know a single solution to list all the called members that are defined in my class (see here: Finding which methods the object has ), I added these simple improvements that exclude __init__ :

 In [244]: [method for method in dir(a) if callable(getattr(a, method)) and not method.startswith('__')] Out[244]: ['say'] 

Compare with:

 In [243]: inspect.getmembers(a) Out[243]: [('__class__', __main__.syncher), ('__delattr__', <method-wrapper '__delattr__' of syncher object at 0xd6d9dd0>), ('__dict__', {'propa': 0, 'propb': 1}), ('__doc__', None), ...snipped ... ('__format__', <function __format__>), ('__getattribute__', <method-wrapper '__getattribute__' of syncher object at 0xd6d9dd0>), ('__hash__', <method-wrapper '__hash__' of syncher object at 0xd6d9dd0>), ('__init__', <bound method syncher.__init__ of <__main__.syncher object at 0xd6d9dd0>>), ('__module__', '__main__'), ('__setattr__', <method-wrapper '__setattr__' of syncher object at 0xd6d9dd0>), ('__weakref__', None), ('propa', 0), ('propb', 1), ('say', <bound method syncher.say of <__main__.syncher object at 0xd6d9dd0>>)] 

or for example:

 In [248]: [method for method in dir(a) if callable(getattr(a, method)) and isinstance(getattr(a, method), types.MethodType)] Out[248]: ['__init__', 'say'] 

and I also found this method that excludes built-in procedures:

 In [258]: inspect.getmembers(a, predicate=inspect.ismethod) Out[258]: [('__init__', <bound method syncher.__init__ of <__main__.syncher object at 0xd6d9dd0>>), ('say', <bound method syncher.say of <__main__.syncher object at 0xd6d9dd0>>)] 

So my question is: do you have a better way to find all methods inside a class (excluding __init__ and all built-in methods) in Python 2.7.X?

+4
source share
1 answer

Since no one else has suggested a better solution, I think Pythonic will be with Python STL:

 inspect.getmembers(a, predicate=inspect.ismethod) 

To exclude init, you can use filter .

+2
source

Source: https://habr.com/ru/post/1485608/


All Articles