type(product.get_datasheet) 显示:
<bound method product.get_datasheet of <pkg.product object at 0x7fbb6c09c290>>
我需要将 product.get_datasheet 与 (ny) 类区分开来。 callable 没有帮助,因为根据 callable 的文档字符串:
Note that classes are callable, as are instances with a __call__() method.
我正在编写类似数据绑定(bind)的东西,我需要在模板中调用绑定(bind)方法,而如果它是一个类,则不应调用它。
如何区分函数或绑定(bind)方法(但不是类方法!)与类?
请您参考如下方法:
给定一个通用类:
>>> class A:
... def __call__(self): pass
...
还有类型模块:
>>> import types
您可以测试一个对象是否是一个函数(callable 为以下所有测试对象返回 True):
>>> isinstance(A, (types.FunctionType, types.BuiltinFunctionType))
False
>>> isinstance(a, (types.FunctionType, types.BuiltinFunctionType))
False
>>> isinstance(A.__call__, (types.FunctionType, types.BuiltinFunctionType))
True
>>> isinstance(a.__call__, (types.FunctionType, types.BuiltinFunctionType))
False
你可以测试一个对象是否是一个方法:
>>> isinstance(A, (types.MethodType, types.BuiltinMethodType))
False
>>> isinstance(a, (types.MethodType, types.BuiltinMethodType))
False
>>> isinstance(A.__call__, (types.MethodType, types.BuiltinMethodType))
False
>>> isinstance(a.__call__, (types.MethodType, types.BuiltinMethodType))
True
所以,如果你想测试一个对象 obj 是否是:
- 职能:
isinstance(obj, (types.FunctionType, types.BuiltinFunctionType))为True
- 方法:
isinstance(obj, (types.MethodType, types.BuiltinMethodType))为True
- 函数或方法:
isinstance(obj, (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType))是True
- 其他可调用对象:
isinstance(obj, (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType))为False- 因此
不是 isinstance(obj, (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType))是True
