python中type和instance
2016-06-14 23:48
453 查看
和Python的new-style class有关。相关链接 http://www.python.org/doc/newstyle/
以下代码在Python2.5中执行:
在old-style class中,任意instance的
另外这个问题又与Python的思想有关,正常情况下不应该编写代码检查类型的,而应该直接假设被操作的instance具有你希望的属性,否则抛出异常。即使需要检查类型,也应该用
参考Duck Typing http://en.wikipedia.org/wiki/Duck_typ...
另外这个问题还与
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 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
以下代码在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 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模板远程代码执行(在不支持多行和exec的情形执行系统命令) 20160614
- PYTHON 获取csdn的博客文章标题和描述
- Python 获取百度的预览图片
- python学习
- 让IIS7.5 执行Python脚本的配置方法
- Python 的Except 异常处理
- Python高级特性
- [leetcode]20. Valid Parentheses ,有效的括号符串python实现【easy】
- [python](爬虫)如何使用正确的姿势欣赏知乎的“长得好看是怎样一种体验呢?”问答中的相片
- python
- Python文件操作汇总
- [leetcode] 17. Letter Combinations of a Phone Number ,python实现【medium】
- Python中的函数
- python生成log文件
- Python核心编程这本书的一些错误
- LeetCode Dungeon Game
- Python 文档处理doctest
- LeetCode Binary Search Tree Iterator
- Python学习笔记(变量类型)