Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在方法中运行时,内置类型()函数的行为不同_Python_Python 3.5 - Fatal编程技术网

Python 在方法中运行时,内置类型()函数的行为不同

Python 在方法中运行时,内置类型()函数的行为不同,python,python-3.5,Python,Python 3.5,我对Python相当陌生,不了解这种行为: In [62]: a = "string" In [63]: type(a)

我对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为什么有一个值类“str”吗

而不是它在ipython3 RAPL-str中的显示方式


谢谢。

您将变量的类型与字符串进行比较,而不是与类型进行比较。只需删除if子句中的引号:

>>> a = "string"
>>> type(a)
<class 'str'>
>>> type(a) == str
True
>>> type(a) == "str"
False

您正在将变量的类型与字符串进行比较,而不是与类型进行比较。只需删除if子句中的引号:

>>> a = "string"
>>> type(a)
<class 'str'>
>>> type(a) == str
True
>>> type(a) == "str"
False

不,没有。在这两种情况下,类型都不等于string str。它等于str类型

在任何情况下,要检查某个内容是否是字符串,您应该再次使用isinstance和实际类型对象

if isinstance(var, str):
    print("it is str")

不,没有。在这两种情况下,类型都不等于string str。它等于str类型

在任何情况下,要检查某个内容是否是字符串,您应该再次使用isinstance和实际类型对象

if isinstance(var, str):
    print("it is str")

这只是IPython展示事物的方式。str不等于“str”:

IPython定义了自己的displayhook,它向您显示结果,在sys中找到的原始displayhook清楚地说明了这一点:

In [15]: sys.__displayhook__(type(''))
<class 'str'>

这只是IPython展示事物的方式。str不等于“str”:

IPython定义了自己的displayhook,它向您显示结果,在sys中找到的原始displayhook清楚地说明了这一点:

In [15]: sys.__displayhook__(type(''))
<class 'str'>

非常感谢大家的澄清。非常感谢大家的澄清。谢谢!我不知道,谢谢!我不知道。我知道isinstance只是决定自己做类似的方法,现在我再一次承认这不是一件好事,谢谢!我知道isinstance只是决定自己做类似的方法,现在我再一次承认这不是一件好事,谢谢!