2009-06-05 1 views
2

클래스의 인스턴스에서 정의 된 함수를 어떻게 동적으로 찾아 낼 수 있습니까? 예를 들어파이썬의 클래스 인스턴스에서 어떤 함수를 사용할 수 있는지 찾아야합니까?

:

이상적으로는 인스턴스가 'A'methodA와 methodB가, 어느 인자가 걸릴 것을 발견 할
class A(object): 
    def methodA(self, intA=1): 
     pass 

    def methodB(self, strB): 
     pass 

a = A() 

?

+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

일부 클래스 migth에는 검사 할 수없는 동적 메서드가 있습니다. 최상의 정보 소스는 여전히 설명서입니다. – nosklo