find all members of an instance in python, excluding __init__
1 2 | In [245]: vars(a) Out[245]: {'propa': 0, 'propb': 1} |
但是,我不知道列出在我的类中定义的所有可调用成员的单一解决方案(请参见此处的示例:查找对象具有哪些方法),我添加了这个简单的改进,其中不包括
1 2 | In [244]: [method for method in dir(a) if callable(getattr(a, method)) and not method.startswith('__')] Out[244]: ['say'] |
比较:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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>>)] |
或例如:
1 2 3 | In [248]: [method for method in dir(a) if callable(getattr(a, method)) and isinstance(getattr(a, method), types.MethodType)] Out[248]: ['__init__', 'say'] |
我还发现了这个方法,它不包括内置例程:
1 2 3 4 5 | 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>>)] |
所以,我的问题是:在python 2.7.x中,是否有更好的方法来查找类中的所有方法(不包括
由于没有其他人能提供更好的解决方案,我想用Python的STL来解决这个问题:
1 | inspect.getmembers(a, predicate=inspect.ismethod) |
要排除init,可以使用