python中type和instance
来源:互联网 发布:怎么登录淘宝网电脑版 编辑:程序博客网 时间:2024/05/16 08:31
和Python的new-style class有关。相关链接 http://www.python.org/doc/newstyle/
以下代码在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了…待补充…
UPDATE:
又找到这段例子,供参考
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 darwinType "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
0 0
- python中type和instance
- Python中isinstance和type进行对比
- Java中instance和instanceof
- Java中instance和instanceof
- python object和type
- Python中有用的三个工具:dir, type和help
- python instance
- Python Instance
- Oracle 中 instance和database的区别
- Python中的 type() 和 __class__
- 简述Python isinstance 和type
- Python type,object和metaclass
- python中的type()和isinstance()
- python的type 和object
- swift中value type和reference type
- java中no enclosing instance of type 在p103 StringHashCode.java
- Java中出现No enclosing instance of type XXX is accessible问题
- Java中出现No enclosing instance of type XXX is accessible问题
- 外键
- 位置函数之坑
- [Java] 往年试卷
- cocos2d理解--SpriteBatchNode和TextureAtlas
- Android Intent意图的常用使用方法
- python中type和instance
- php中数组的数组元素最多出现2次,出现3次了就把第三次的数组元素去掉
- LeetCode-237 Delete Node in a Linked List
- 练习4-3 在有了基本框架后,对计算器程序进行扩充就比较简单了。在该程序中加入取模(%)运算符,并注意考虑负数的情况
- The Hello Wayland Tutorial
- SQL 行列转换
- WebService的两种方式SOAP和REST比较
- mysql常用基础操作语法(三)~~对数据的增删改操作【命令行模式】
- ubuntu下编译openjdk7