Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.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 - Fatal编程技术网

Python 如何测试对象的类型?

Python 如何测试对象的类型?,python,Python,我对python中“if”语句中的类型测试感到困惑。例如,在以下代码中: x=10 if [isinstance(x, str)]: print('yes') else: print('no') 输出为“是”。x=10是一个整数,不是字符串,但为什么代码会给出“是” 非常感谢仅使用isinstance(x,str)它将执行您期望的答案。在中设置条件时,如果[isinstance(x,str)]则会打印YES,因为[isinstance(x,str)]返回一个布尔列表的TRUE。

我对python中“if”语句中的类型测试感到困惑。例如,在以下代码中:

x=10
if [isinstance(x, str)]:
    print('yes')
else:
    print('no')
输出为“是”。x=10是一个整数,不是字符串,但为什么代码会给出“是”

非常感谢

仅使用
isinstance(x,str)
它将执行您期望的答案。在
中设置条件时,如果[isinstance(x,str)]
则会打印
YES
,因为
[isinstance(x,str)]
返回一个布尔列表的TRUE。因为列表不是空的,所以它会打印
YES

print([isinstance(x, str)])

# Output
# [False]

这里的
[False]
是一个布尔列表。

这是因为你把这个布尔值,它是False,放在一个列表中,现在python会检查
len([isinstance(x,str)])>0
既然是这样,它会打印“yes”

这很好,[isinstance(x,str)]返回true,因为列表不是空的

x=10
if isinstance(x, str):
    print('yes')
else:
    print('no')
if-isinstance(x,str)
而不是
if[isinstance(x,str)]