2011-12-07 27 views
2

檢測結合方法在類(未實例)給定一個類C與函數或方法f,我使用inspect.ismethod(obj.f)(其中objC一個實例),以找出是否f綁定方法或沒有。有沒有辦法直接在課堂上做同樣的事情(不需要創建對象)?在此在Python 3

class C(object): 

    @staticmethod 
    def st(x): 
     pass 

    def me(self): 
     pass 

obj = C() 

結果(在Python 3)::我想我需要檢查是否的功能/方法是構件

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

inspect.ismethod不起作用,因爲這一個班級,而不是靜態的,但我無法輕鬆完成。我想這可以使用classify_class_attrs來完成,如這裏所示 How would you determine where each property and method of a Python class is defined? 但我希望有另一種更直接的方法。

回答

2

Python 3中沒有未綁定的方法,因此您也無法檢測到它們。你所擁有的只是常規功能。最多,你可以看到,如果他們有一個qualified name with a dot,表明它們是嵌套,他們的第一個參數的名字是self

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

這當然完全失敗,對於正好有self靜態方法和嵌套函數作爲第一個參數,以及不使用self作爲第一個參數的常規方法(面向約定飛行)。

對於靜態方法和類方法,你必須看看類字典代替:

>>> isinstance(vars(C)['st'], staticmethod) 
True 

這是因爲C.__dict__['st']是實際staticmethod實例,binding to the class之前。

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.isroutine(...)結果與inspect.ismethod(...)結果可能使您能夠推斷出你所需要知道的。

編輯: 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對於Python 2.7中的綁定和非綁定方法(即破壞),我正在使用:

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

它也適用於在C語言實現的類,例如使用的方法,INT:

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

但不是在這種情況下非常有用,因爲inspect.getargspec不適合用C實現職能的工作

is_bound_method作品在Python 3中保持不變,但在Python 3中,inspect.ismethod正確地區分了綁定和未綁定的方法,因此不是必需的。

+0

這隻對Python ** two **有用,而具體詢問Python ** 3 **的問題,沒有未綁定的方法。 –