虚位以待(AD)
虚位以待(AD)
首页 > 脚本专栏 > python > 浅谈Python中重载isinstance继承关系的问题

浅谈Python中重载isinstance继承关系的问题
类别:python   作者:码皇   来源:互联网   点击:

本篇文章主要介绍了浅谈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): passb = B()print(isinstance(b, Sizeable)) # output:False

只打印了 False,并且 __instancecheck__ 没有调用。 这是怎么回事。

没有运行的 __instancecheck__

可见文档写得并不清楚,为了找出问题,我们从 isinstance 源码开始进行跟踪。

    [abstract.c]intPyObject_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) 行为的条件:

  1. x 对象不能是由 C 直接实例化;
  2. C 类指定 metaclass ;
  3. 指定的 metaclass 类中定义了 __instancecheck__ 。

测试代码:

    class MetaSizeable(type): def __instancecheck__(cls, instance): print("__instancecheck__ call") return hasattr(instance, "__len__")class Sizeable(metaclass=MetaSizeable): passclass B(object): passb = B()print(isinstance(b, Sizeable)) # output: Falseprint(isinstance([], Sizeable)) # output: True

文档可能有点老旧了。本次测试的环境是Python3.6。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

  • python面向对象_详谈类的继承与方法的重载
相关热词搜索: Python 重载 继承 Python isinstance