浅谈Python中重载isinstance继承关系的问题


本文摘自php中文网,作者不言,侵删。

这篇文章主要介绍了关于浅谈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) ,返回的结果便是实例检测的结果,默认的判断方式就没有了。

这种方式有助于我们来检查鸭子类型,我用代码测了一下。

1

2

3

4

5

6

7

8

9

10

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 源码开始进行跟踪。

1

2

3

4

5

6

7

8

9

10

11

12

[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__ 有误。继续向下看源码:

1

2

3

4

/* We know what type's __instancecheck__ does. */

if (PyType_CheckExact(cls)) {

  return recursive_isinstance(inst, cls);

}

展开宏 PyType_CheckExact :

1

2

[object.h]

#define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type)

也就是说 cls 是由 type 直接构造出来的类,则判断语言成立。除了类声明里指定 metaclass 外基本都是由 type 直接构造的。从测试代码中得知判断成立,进入 recursive_isinstance。但是这个函数里面我却没找到有关 __instancecheck__ 的代码,recursive_isinstance 的判断逻辑大致是:

1

2

3

4

5

6

7

8

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 函数往下看:

1

2

3

if (PyTuple_Check(cls)) {

  ...

}

这是当 instance(x, C) 第二个参数是元组的情况,里面的处理方式是递归调用 PyObject_IsInstance(inst, item) 。继续往下看:

1

2

3

4

5

6

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 就可以了:

1

2

3

4

5

6

7

8

9

10

11

[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__ 。

测试代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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继承关系的问题的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

人生苦短,学习Python

Python中迭代相关的简单介绍(附代码)

Python对字符串实现重操作方法讲解

Python中的字典排序如何实现代码说明

django中数据库设置的详细介绍(代码示例)

Python如何查找字符串的长度?(代码示例)

交叉验证以及Python代码实现

Python中数据类型时间的介绍(附代码)

Python单词怎么读

Python3列表的基础学习(附示例)

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...