基本上我想这样做:
obj = 'str'
type ( obj ) == string
我试过:
type ( obj ) == type ( string )
它没有用。
另外,其他类型呢?例如,我无法复制 NoneType
。
原文由 Joan Venge 发布,翻译遵循 CC BY-SA 4.0 许可协议
基本上我想这样做:
obj = 'str'
type ( obj ) == string
我试过:
type ( obj ) == type ( string )
它没有用。
另外,其他类型呢?例如,我无法复制 NoneType
。
原文由 Joan Venge 发布,翻译遵循 CC BY-SA 4.0 许可协议
首先,避免所有类型比较。它们非常非常少是必需的。有时,它们有助于检查函数中的参数类型——即使这种情况很少见。错误类型的数据会引发异常,这就是您所需要的。
所有基本转换函数都将映射为等于类型函数。
type(9) is int
type(2.5) is float
type('x') is str
type(u'x') is unicode
type(2+3j) is complex
还有其他一些情况。
isinstance( 'x', basestring )
isinstance( u'u', basestring )
isinstance( 9, int )
isinstance( 2.5, float )
isinstance( (2+3j), complex )
没有,顺便说一句,从来不需要任何这种类型检查。 None 是 NoneType 的唯一实例。 None 对象是一个单例。只需检查无
variable is None
顺便说一句,一般不要使用上面的。使用普通异常和 Python 自身的天然多态性。
原文由 S.Lott 发布,翻译遵循 CC BY-SA 2.5 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
2 回答855 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
在您的情况下,
isinstance("this is a string", str)
将返回True
。您可能还想阅读此内容:http: //www.canonical.org/~kragen/isinstance/