【问题标题】:Finding out which functions are available from a class instance in python?在 python 的类实例中找出哪些函数可用?
【发布时间】:2010-10-31 15:07:06
【问题描述】:

如何动态地找出从类的实例中定义了哪些函数?

例如:

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

    def methodB(self, strB):
        pass

a = A()

理想情况下,我想知道实例“a”有methodA和methodB,它们采用哪些参数?

【问题讨论】:

标签: python introspection


【解决方案1】:

看看inspect 模块。

>>> 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.

【讨论】:

  • inspect.getmembers() 和 dir() 有区别
  • @Adrian: dir() 只返回名称。 inspect.getmembers() 也返回实际成员。
  • 请注意,某些类可能具有无法检查的动态方法 - 最好的信息来源仍然是文档。
猜你喜欢
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
  • 1970-01-01
相关资源
最近更新 更多