2011-12-07 1 views
2

의 클래스 (없는 경우)에 바인딩 된 메서드를 감지, 나는 f이 방법을 구속 여부되어 있는지 확인하기 위해 (objC의 인스턴스) inspect.ismethod(obj.f)를 사용합니다. 객체를 만들지 않고 클래스 수준에서 직접 동일한 작업을 수행 할 수 있습니까?함수 또는 메소드 <code>f</code>와 클래스 <code>C</code>을 감안할 때 파이썬 3

inspect.ismethod이 작동하지 않습니다

class C(object): 

    @staticmethod 
    def st(x): 
     pass 

    def me(self): 
     pass 

obj = C() 

결과를이에 (파이썬 3) :

>>> inspect.ismethod(C.st) 
False 
>>> inspect.ismethod(C.me) 
False 
>>> inspect.ismethod(obj.st) 
False 
>>> inspect.ismethod(obj.me) 
True 

을 내가 기능/방법의 구성원인지 확인해야 추측 클래스가 아닌 정적이지만 쉽게 할 수 없었습니다. 여기에 표시된대로 classify_class_attrs을 사용하여 작업을 완료 할 수 있다고 생각합니다. How would you determine where each property and method of a Python class is defined? 그러나 나는 다른 직접적인 방법이 더 있었으면합니다.

답변

2

파이썬 3에는 언 바운드 (unbound) 메소드가 없으므로이를 감지 할 수 없습니다. 정규 기능 만 있으면됩니다.

물론
if '.' in method.__qualname__ and inspect.getargspec(method).args[0] == 'self': 
    # regular method. *Probably* 

self이 일이 정적 메서드와 중첩 된 기능에 완전히 실패 그들이 qualified name with a dot이있는 경우 대부분에서 당신은 그들이 을 중첩하고, 자신의 첫 번째 인수의 이름은 self 것을 나타내는 볼 수 있습니다 첫 번째 인수로서 self을 첫 번째 인수로 사용하지 않는 규칙적인 메소드 (규칙에 따라).메소드와 클래스 메소드 정적에 대한

, 대신 클래스 사전보고해야 할 것 :

C.__dict__['st']binding to the class 전에, 실제 staticmethod 예이기 때문이다
>>> isinstance(vars(C)['st'], staticmethod) 
True 

.

0

inspect.isroutine(...)을 사용할 수 있습니까? 내가 할 C 클래스로 실행 :

>>> inspect.isroutine(C.st) 
True 
>>> inspect.isroutine(C.me) 
True 
>>> inspect.isroutine(obj.st) 
True 
>>> inspect.isroutine(obj.me) 
True 

inspect.ismethod(...)의 결과 inspect.isroutine(...)의 결과를 결합하는 것은 당신이 알아야 할 어떤 추론을 가능하게 할 수있다.

편집 : dm03514의 대답은 당신이 또한 inspect.isfunction()을 시도 할 수 있습니다 제안 :

>>> inspect.isfunction(obj.me) 
False 
>>> inspect.isfunction(obj.st) 
True 
>>> inspect.isfunction(C.st) 
True 
>>> inspect.isfunction(C.me) 
False 

비록 에르난는 지적으로, 파이썬 inspect.isfunction(...) 변화의 결과 3.

0

inspect.ismethod True를 반환하기 때문에 파이썬 2.7에서 바인드 된 메소드와 언 바운드 메소드 모두 (즉, 깨졌습니다.)를 사용하고 있습니다 :

def is_bound_method(obj): 
    return hasattr(obj, '__self__') and obj.__self__ is not None 

또한, 예를 들어, C에서 구현 클래스의 방법을 작동 값 int : inspect.getargspec는 C로 구현 기능이 작동하지 않기 때문에

>>> a = 1 
>>> is_bound_method(a.__add__) 
True 
>>> is_bound_method(int.__add__) 
False 

는하지만 경우에 매우 유용하지 않습니다

is_bound_method 작품 파이썬 3에서는 변경되지 않았지만 파이썬 3에서는 inspect.ismethod가 바운드 메소드와 언 바운드 메소드를 적절히 구분하므로 필요하지 않습니다.

+0

이것은 Python ** two **에만 유용하지만, 언 바운드 방식이없는 Python ** three **에 관해서는 특별히 묻습니다. –