Python 判断变量类型用instance而不用type
2017-03-07 00:00
801 查看
和Python的new-style class有关。相关链接 http://www.python.org/doc/newstyle/
以下代码在Python2.5中执行:
在old-style class中,任意instance的type都是'instance'。所以绝对不能用type来判断其类型。
另外这个问题又与Python的思想有关,正常情况下不应该编写代码检查类型的,而应该直接假设被操作的instance具有你希望的属性,否则抛出异常。即使需要检查类型,也应该用isinstance来判断,这样你期望类型的subclass也能正常被处理(比如,一个函数需要处理Message类型,那么它应该也能处理Message的子类型MyMessage,所以应该使用isinstance(arg,Message)这样来判断而不是type(arg) == Message来判断)
参考Duck Typing http://en.wikipedia.org/wiki/Duck_typ...
另外这个问题还与metaclass有关,但是我实在想不起来在哪个地方会导致type()返回的不是type这个class的instance了…待补充…
以下代码在Python2.5中执行:
>>> class A: ... pass ... >>> a = A() >>> class B: ... pass ... >>> b = B() >>> type(a) is type(b) True >>>
在old-style class中,任意instance的type都是'instance'。所以绝对不能用type来判断其类型。
另外这个问题又与Python的思想有关,正常情况下不应该编写代码检查类型的,而应该直接假设被操作的instance具有你希望的属性,否则抛出异常。即使需要检查类型,也应该用isinstance来判断,这样你期望类型的subclass也能正常被处理(比如,一个函数需要处理Message类型,那么它应该也能处理Message的子类型MyMessage,所以应该使用isinstance(arg,Message)这样来判断而不是type(arg) == Message来判断)
参考Duck Typing http://en.wikipedia.org/wiki/Duck_typ...
另外这个问题还与metaclass有关,但是我实在想不起来在哪个地方会导致type()返回的不是type这个class的instance了…待补充…
Python 2.7.3 (default, May 12 2012, 00:10:31) [GCC 4.2.1 (Gentoo 4.2.1_p5666, Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from collections import Iterator >>> class A(object): ... def __iter__(self): ... pass ... def next(self): ... pass ... >>> isinstance(A(), Iterator) True
相关文章推荐
- python判断变量类型时,为什么不推荐使用type()方法
- Python 继承、多重继承、多态、isinstance判断类型、type()获取变量类型、dir()获取变量的所有属性
- python不使用type(obj) is **来判断变量的类型
- python判断变量类型时,为什么不推荐使用type()方法
- Python中请使用isinstance()判断变量类型
- Flex的四种判断对象类型的方式 as instanceof is typeof比较
- Python中请使用isinstance()判断变量类型
- python判断类型:想知道一个对象(实例或者变量)是什么类型,什么结构的
- python 判断变量类型
- Python 判断变量的数据类型
- python中如何判断一个变量的数据类型
- python判断类型:想知道一个对象(实例或者变量)是什么类型,什么结构的
- javascript类型判断 typeof instanceof constructor
- Python学习--判断变量的数据类型
- Python isinstance判断对象类型
- 判断js中的类型:typeof / instanceof / constructor / prototype
- jquery判断变量类型typeof和Object.prototype.toString.apply()
- python中如何判断变量的数据类型
- python中如何判断一个变量的数据类型
- typeof + instanceof+toString+constructor是如何判断javascript数据类型的