判断一个类的成员是否是一个方法的最pythonic方式是什么?注意:我只有(可能的)方法的名称(可以是类方法、实例方法 或静态方法)。
目前我正在比较类字典中对象的类型与<type 'function'> :
def isMethodOf(methodName,klass):
return type(klass.__dict__.get(methodName)) == type(lambda x:x)
我真的不知道这是否适用于所有情况。 type(lambda x:x)部分仅用于获取类型 <type 'function'> , 有更好的方法吗?
请您参考如下方法:
在 Python 2 上,使用 inspect.ismethod() :
return inspect.ismethod(getattr(klass, methodName))
对于 Python 3,未绑定(bind)的方法消失了,您将使用 inspect.isfunction()相反。
您还可以使用 types.MethodType type object测试:
import types
isinstance(getattr(klass, methodName), types.MethodType)
这两个测试都适用于 @classmethod 方法和常规方法。 按照设计,这些测试对于 @staticmethod 方法会失败;这些只是抵抗绑定(bind)的函数(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 种方法“类型”以及上述自定义对象。请注意,作为工厂的类也是可调用的。
