Finding out which functions are available from a class instance in python?

白昼怎懂夜的黑 提交于 2020-01-01 19:06:09

问题


How do you dynamically find out which functions have been defined from an instance of a class?

For example:

class A(object):
    def methodA(self, intA=1):
        pass

    def methodB(self, strB):
        pass

a = A()

Ideally I want to find out that the instance 'a' has methodA and methodB, and which arguments they take?


回答1:


Have a look at the inspect module.

>>> import inspect
>>> inspect.getmembers(a)
[('__class__', <class '__main__.A'>),
 ('__delattr__', <method-wrapper '__delattr__' of A object at 0xb77d48ac>),
 ('__dict__', {}),
 ('__doc__', None),
 ('__getattribute__',
  <method-wrapper '__getattribute__' of A object at 0xb77d48ac>),
 ('__hash__', <method-wrapper '__hash__' of A object at 0xb77d48ac>),
 ('__init__', <method-wrapper '__init__' of A object at 0xb77d48ac>),
 ('__module__', '__main__'),
 ('__new__', <built-in method __new__ of type object at 0x8146220>),
 ('__reduce__', <built-in method __reduce__ of A object at 0xb77d48ac>),
 ('__reduce_ex__', <built-in method __reduce_ex__ of A object at 0xb77d48ac>),
 ('__repr__', <method-wrapper '__repr__' of A object at 0xb77d48ac>),
 ('__setattr__', <method-wrapper '__setattr__' of A object at 0xb77d48ac>),
 ('__str__', <method-wrapper '__str__' of A object at 0xb77d48ac>),
 ('__weakref__', None),
 ('methodA', <bound method A.methodA of <__main__.A object at 0xb77d48ac>>),
 ('methodB', <bound method A.methodB of <__main__.A object at 0xb77d48ac>>)]
>>> inspect.getargspec(a.methodA)
(['self', 'intA'], None, None, (1,))
>>> inspect.getargspec(getattr(a, 'methodA'))
(['self', 'intA'], None, None, (1,))
>>> print inspect.getargspec.__doc__
Get the names and default values of a function's arguments.

    A tuple of four things is returned: (args, varargs, varkw, defaults).
    'args' is a list of the argument names (it may contain nested lists).
    'varargs' and 'varkw' are the names of the * and ** arguments or None.
    'defaults' is an n-tuple of the default values of the last n arguments.
>>> print inspect.getmembers.__doc__
Return all members of an object as (name, value) pairs sorted by name.
    Optionally, only return members that satisfy a given predicate.


来源:https://stackoverflow.com/questions/955533/finding-out-which-functions-are-available-from-a-class-instance-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!