我是 Python 的新手,我不明白这种行为:
In [62]: a = "string"
In [63]: type(a)
Out[63]: str
In [64]: def some_method(what):
var = type(what)
if var == "str":
print("it is str")
else:
print("it's NOT str")
print("Val of passed arg is - ", what, "And 'var' is - ", var)
In [65]: some_method(a)
it's NOT str
Val of passed arg is - string And 'var' is - <class 'str'>
谁能解释为什么变量“var”的值是“class 'str'”,
而不是它在 ipython3 RAPL 中的显示方式 - “str”?
谢谢。
最佳答案
不,它没有。在这两种情况下,类型都不等于字符串 "str"
。它等于类型 str
。
无论如何,要检查某物是否为字符串,您应该使用 isinstance
,再次使用实际类型对象。
if isinstance(var, str):
print("it is str")
关于python - 在方法中运行时,内置 type() 函数的行为有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47873616/