这篇文章主要介绍了关于浅谈python中重载isinstance继承关系的问题,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
判断继承关系
通过内建方法 isinstance(object, classinfo) 可以判断一个对象是否是某个类的实例。这个关系可以是直接,间接或抽象。
实例的检查是允许重载的,可见文档customizing-instance-and-subclass-checks 。根据 pep 3119 的描述:
the primary mechanism proposed here is to allow overloading the built-in functions isinstance() and issubclass(). the overloading works as follows: the call isinstance(x, c) first checks whether c.__instancecheck__ exists, and if so, calls c.__instancecheck__(x) instead of its normal implementation.
这段话的意思是,当调用 isinstance(x, c) 进行检测时,会优先检查是否存在 c.__instancecheck__ ,如果存在则调用 c.__instancecheck__(x) ,返回的结果便是实例检测的结果,默认的判断方式就没有了。
这种方式有助于我们来检查鸭子类型,我用代码测了一下。
class sizeable(object):
def __instancecheck__(cls, instance):
print("__instancecheck__ call")
return hasattr(instance, "__len__")
class b(object):
pass
b = b()
print(isinstance(b, sizeable)) # output:false
只打印了 false,并且 __instancecheck__ 没有调用。 这是怎么回事。
没有运行的 __instancecheck__
可见文档写得并不清楚,为了找出问题,我们从 isinstance 源码开始进行跟踪。
[abstract.c]
int
pyobject_isinstance(pyobject *inst, pyobject *cls)
{
_py_identifier(__instancecheck__);
pyobject *checker;
/* quick test for an exact match */
if (py_type(inst) == (pytypeobject *)cls)
return 1;
....
}
py_type(inst) == (pytypeobject *)cls 这是一种快速匹配的方式,等价于 type(inst) is cls ,这种快速的方式匹配成功的话,也不会去检查 __instancecheck__ 。所以文档中的优先检查是否存在 c.__instancecheck__ 有误。继续向下看源码:
/* we know what type's __instancecheck__ does. */
if (pytype_checkexact(cls)) {
return recursive_isinstance(inst, cls);
}
展开宏 pytype_checkexact :
[object.h]
#define pytype_checkexact(op) (py_type(op) == &pytype_type)
也就是说 cls 是由 type 直接构造出来的类,则判断语言成立。除了类声明里指定 metaclass 外基本都是由 type 直接构造的。从测试代码中得知判断成立,进入 recursive_isinstance。但是这个函数里面我却没找到有关 __instancecheck__ 的代码,recursive_isinstance 的判断逻辑大致是:
def recursive_isinstance(inst, cls):
return pytype_issubtype(inst, cls)
def pytype_issubtype(a, b):
for mro in a.__mro__:
if mro is b:
return true
return false
是从 __mro__ 继承顺序来判断的。回到 pyobject_isinstance 函数往下看:
if (pytuple_check(cls)) {
...
}
这是当 instance(x, c) 第二个参数是元组的情况,里面的处理方式是递归调用 pyobject_isinstance(inst, item) 。继续往下看:
checker = _pyobject_lookupspecial(cls, &pyid___instancecheck__);
if (checker != null) {
res = pyobject_callfunctionobjargs(checker, inst, null);
ok = pyobject_istrue(res);
return ok;
}
显然,这边才是获得 __instancecheck__ 的地方,为了让检查流程走到这里,定义的类要指明 metaclass 。剩下就是跟踪下 _pyobject_lookupspecial 就可以了:
[typeobject.c]
pyobject *
_pyobject_lookupspecial(pyobject *self, _py_identifier *attrid)
{
pyobject *res;
res = _pytype_lookupid(py_type(self), attrid);
// 有回调的话处理回调
// ...
return res;
}
取的是 py_type(self) ,也就是说指定的 metaclass 里面需要定义 __instancecheck__ 。
总结
至此,总结一下要重载 isinstance(x, c) 行为的条件:
x 对象不能是由 c 直接实例化;
c 类指定 metaclass ;
指定的 metaclass 类中定义了 __instancecheck__ 。
测试代码:
class metasizeable(type):
def __instancecheck__(cls, instance):
print("__instancecheck__ call")
return hasattr(instance, "__len__")
class sizeable(metaclass=metasizeable):
pass
class b(object):
pass
b = b()
print(isinstance(b, sizeable)) # output: false
print(isinstance([], sizeable)) # output: true
文档可能有点老旧了。本次测试的环境是python3.6。
相关推荐:
对python 2.7 pandas 中的read_excel详解
以上就是浅谈python中重载isinstance继承关系的问题的详细内容。