为什么类型检查对 returns 类型不起作用?

Why does type checking not work for what type returns?

我刚刚尝试测试:

if type(model_lines) == 'str':
    turn into a list using split

基于:

In [196]: type('a')
Out[196]: str

然而,对于 x,一个字符串:

In [193]: if type(x) == 'str':
    print 'string'
   .....:  

In [195]: if type(x) == type('a'):
    print 'string'
   .....:     
string

我很好奇为什么我不能使用这个输出来检查类型,它看起来更清晰,阅读起来更快。实际上 return 不允许通过其 return 显示进行检查的类型是什么?

因为,type() return 是对象的 class,而不是 class 的字符串名称,所以如果您执行类似下面的操作,它会工作-

>>> if type('abcd') == str:
...     print("Blah")
...
Blah
>>> type('abcd')
<class 'str'>

如上所述,我检查了 type('abcd') 的 return 与 str class 的对比,而不是字符串 'str' .

如果您想要 class 的字符串表示形式,请使用 tpye(<something>).__name__ 来获取 class 的字符串名称,尽管您的情况不需要这样做,只是为了你的资料。示例 -

>>> type('abcd').__name__
'str'

因为type('a')也可以产生unicode实例。您可以通过查看 type('a').

的输出来断言这一点