2009-06-05 9 views
2

クラスのインスタンスから定義された関数をどのように動的に見つけ出すのですか?例えばPythonでクラスインスタンスから利用できる関数を見つけるには?

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

    def methodB(self, strB): 
     pass 

a = A() 

は、理想的には、私はインスタンスは「」methodAとmethodBを持っていること、そして彼らが取るどの引数知りたいですか?

+0

は、検査の間に差があるhttp://stackoverflow.com/questions/546337/how-do-i-perform-introspection-on-an-object-in-python-2-x –

答えて

12

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

を参照してください。 getmembers()とdir() –

+0

@Adrian:dir()は名前を返します。 inspect.getmembers()は実際のメンバーも返します。 – RichieHindle

+0

いくつかのクラスは、検査できない動的メソッドを持っていることに注意してください。最良の情報源は依然としてドキュメントです。 – nosklo

関連する問題