Skip to main content
 首页 » 编程设计

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

2025年05月04日13qq78292959

我是 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")