基本上我想这样做:
obj = 'str'
type ( obj ) == string
我试着:
type ( obj ) == type ( string )
但这并没有起作用。
还有,其他类型的呢?例如,我无法复制NoneType。
基本上我想这样做:
obj = 'str'
type ( obj ) == string
我试着:
type ( obj ) == type ( string )
但这并没有起作用。
还有,其他类型的呢?例如,我无法复制NoneType。
当前回答
isinstance()
在你的例子中,isinstance("this is a string", str)将返回True。
你可能还想读这个:http://www.canonical.org/~kragen/isinstance/
其他回答
isinstance工作原理:
if isinstance(obj, MyClass): do_foo(obj)
但是,请记住:如果它看起来像鸭子,如果它听起来像鸭子,它就是鸭子。
编辑:对于None类型,你可以简单地做:
if obj is None: obj = MyClass()
使用str代替string
type ( obj ) == str
解释
>>> a = "Hello"
>>> type(a)==str
True
>>> type(a)
<type 'str'>
>>>
因为type返回一个对象,所以可以使用object.name访问对象的名称
例子:
years = 5
user = {'name':'Smith', 'age':20}
print(type(a).__name__)
输出:“int”
print(type(b).__name__ )
输出:“东西”
您总是可以使用type(x) == type(y)技巧,其中y是具有已知类型的东西。
# check if x is a regular string
type(x) == type('')
# check if x is an integer
type(x) == type(1)
# check if x is a NoneType
type(x) == type(None)
通常有更好的方法来做到这一点,特别是对于任何最新的python。但如果你只想记住一件事,你可以记住它。
在这种情况下,更好的方法是:
# check if x is a regular string
type(x) == str
# check if x is either a regular string or a unicode string
type(x) in [str, unicode]
# alternatively:
isinstance(x, basestring)
# check if x is an integer
type(x) == int
# check if x is a NoneType
x is None
注意最后一种情况:在python中只有一个NoneType实例,那就是None。你会在异常中看到很多NoneType (TypeError: 'NoneType'对象是不可下标的-发生在我身上..),但你几乎不需要在代码中引用它。
最后,正如fengshaun所指出的,python中的类型检查并不总是一个好主意。更python化的做法是只使用值,就好像它是您所期望的类型一样,并捕获(或允许传播)由此产生的异常。
你很接近了!字符串是模块,不是类型。你可能想比较obj的类型和字符串的类型对象,即str:
type(obj) == str # this works because str is already a type
另外:
type(obj) == type('')
注意,在python2中,如果obj是unicode类型,那么上述两种方法都不能工作。isinstance()也不会。看看约翰对这篇文章的评论,了解如何解决这个问题……我已经试着记住它大约10分钟了,但是有一个记忆块!