2009-07-07 86 views
3

在Python中,我需要高效並一般地測試某個類的屬性是否爲實例方法。調用的輸入將是被檢查的屬性(一個字符串)和一個對象的名稱。如何測試類屬性是否是實例方法

無論屬性是否爲實例方法,hasattr都會返回true。

有什麼建議嗎?


例如:如果該屬性存在,然後如果該屬性檢查

class A(object): 
    def method_name(self): 
     pass 


import inspect 

print inspect.ismethod(getattr(A, 'method_name')) # prints True 
a = A() 
print inspect.ismethod(getattr(a, 'method_name')) # prints True 
+1

你確定你需要知道它是一種方法嗎?你真的很想知道你能否打電話嗎?這些不一定是相同的東西(儘管它們通常是)。 – 2009-07-07 09:40:20

+0

閱讀源代碼有什麼問題?這是Python - 你有來源 - 爲什麼你不能簡單地閱讀它? – 2009-07-07 11:31:32

回答

10
def hasmethod(obj, name): 
    return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType 
4
import types 

print isinstance(getattr(your_object, "your_attribute"), types.MethodType) 
4

可以使用inspect模塊是一種使用該方法的方法inspect模塊。

import inspect 

def ismethod(obj, name): 
    if hasattr(obj, name): 
     if inspect.ismethod(getattr(obj, name)): 
      return True 
    return False 

class Foo: 
    x = 0 
    def bar(self): 
     pass 

foo = Foo() 
print ismethod(foo, "spam") 
print ismethod(foo, "x") 
print ismethod(foo, "bar") 
1

此功能檢查:

class Test(object): 
    testdata = 123 

    def testmethod(self): 
     pass 

test = Test() 
print ismethod(test, 'testdata') # Should return false 
print ismethod(test, 'testmethod') # Should return true 
相關問題