Python 如何测试对象的类型?
我对python中“if”语句中的类型测试感到困惑。例如,在以下代码中: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。
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)]