在Python 2中,使用inspect.ismethod()
:
return inspect.ismethod(getattr(klass, methodName))
對於Python 3,非綁定方法都走了,你會使用inspect.isfunction()
代替。
您還可以使用types.MethodType
type object再次進行測試:
import types
isinstance(getattr(klass, methodName), types.MethodType)
兩個試驗@classmethod
方法和常規方法的工作。 按設計這些測試對於@staticmethod
方法失敗;這些只是抵制綁定的函數(cls.staticmethod.__get__(instance, cls)
返回函數本身)。您可以使用inspect.isfunction()
測試功能,或使用isinstance(obj, (types.MethodType, types.FunctionType))
在一次測試中捕獲所有3個功能。
如果您只想測試是否可以調用,則可以使用callable()
function。它會工作,即使對象是一個實例與__call__
方法:
>>> class MyCallable(object):
... def __call__(self):
... return "Hello World!"
...
>>> mc = MyCallable()
>>> callable(mc)
True
>>> mc()
'Hello World!'
使用callable()
作品在所有3個方法「類型」以及自定義對象,如上述。請注意,類,作爲工廠,也可以調用。
['inspect.ismethod'](http://docs.python.org/2/library/inspect.html#inspect.ismethod) – roippi