python - 在方法中运行时,内置 type() 函数的行为有所不同

标签 python python-3.5

我是 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/

相关文章:

Python请求GET需要很长时间才能响应一些请求

numpy - "OSError: cannot write object arrays to a file in binary mode"

python - 有效地将列表转换为数据框

python - 如何从列 pyspark 中获得第二高的值?

python - 检测 Pandas 中缺失的列标签

asynchronous - 我可以将 async 和 wait 与 Tornado-redis 一起使用吗? (Python 3.5)

python - 如何在 Python 中集成 beta 发行版

python - Python 中的多处理池 - 仅使用单个 CPU

python - python 3.5 中的 zip 函数具有超过 255 个参数

python - 使用 python 3.5 安装 cPickle