【问题标题】:Difference between isinstance and type in python [duplicate]python中isinstance和type之间的区别[重复]
【发布时间】:2015-07-26 19:09:15
【问题描述】:

我在网上看一些代码,我看到了一些我不习惯的代码。最引起我注意的是:

if not isinstance(string, str):
    #dosomething

如果我这样做会有什么不同:

if type(string)!=str:
    #dosomething

【问题讨论】:

  • 一般建议:当您有 python 问题时,请使用 python 标签。如果问题是特定于 python-3.x 的,请使用这两个标签。这应该会增加观众的数量。

标签: python python-3.x types


【解决方案1】:

首先查看所有出色的答案here

type() 只返回对象的类型。鉴于,isinstance()

如果 object 参数是 classinfo 参数或其(直接、间接或虚拟)子类的实例,则返回 true。

例子:

class MyString(str):
    pass

my_str = MyString()
if type(my_str) == 'str':
    print 'I hope this prints'
else:
    print 'cannot check subclasses'
if isinstance(my_str, str):
    print 'definitely prints'

打印:

cannot check subclasses
definitely prints

【讨论】:

  • 欢迎评论为什么你会投反对票。
猜你喜欢
  • 2020-11-14
  • 2016-09-02
  • 2022-01-14
  • 2016-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
相关资源
最近更新 更多