python判断变量类型时,为什么不推荐使用type()方法

用type()这种判断变量的方法,结果老鸟被鄙视了,不知所以然。
求各位讲解:这个问题出在哪里,怎样判断一个变量的类型才是好方法?

>>> n = 911
>>> type(n)
<type 'int'>
>>> type(n) is int
True

和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 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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值