简体   繁体   English

Python - isinstance返回false

[英]Python - isinstance returns false

I'm having an issue with isinstance() . 我遇到了isinstance()的问题。

I'm using Python 2.7.8, and running scripts from the shell. 我正在使用Python 2.7.8,并从shell运行脚本。

The array element I'm testing for contains a number, but this function returns false; 我正在测试的array元素包含一个数字,但是这个函数返回false; using number.Numbers : 使用number.Numbers

import numbers
...
print array[x][i] 
>> 1
...
print isinstance(array[x][i], numbers.Number)
>>> False

Also tried this, from this post 也试过这个,从这篇文章

import types
...
print isinstance(array[x][i], (types.IntType, types.LongType, types.FloatType, types.ComplexType))
>>> False

From the same post, I tried 从同一篇文章中,我试过了

isinstance(array[x][i], (int, float, long, complex))

I also tried this solution did not work. 我也试过这个解决方案没有用。

All return false. 全部归还错误。

You don't have a number; 你没有号码; you most probably have a string instead, containing the digit '1' : 很可能有一个字符串,包含数字'1'

>>> value = '1'
>>> print value
1
>>> print 1
1

This is not a number; 这不是一个数字; it is a string instead. 它是一个字符串。 Note that printing that string is indistinguishable from printing an integer. 请注意, 打印该字符串与打印整数无法区分。

Use repr() to print out Python representations instead, and / or use the type() function to produce the type object for a given value: 使用repr()代替打印出Python表示 ,和/或使用type()函数为给定值生成类型对象:

>>> print repr(value)
'1'
>>> print type(value)
<type 'str'>

Now it is clear that the value is a string, not an integer, even though it looks the same when printed. 现在很清楚,该值是一个字符串,而不是一个整数,即使它在打印时看起来相同。

For actual numeric values, isinstance() together with numbers.Number works as expected: 对于实际数值, isinstance()numbers.Number按预期工作:

>>> from numbers import Number
>>> isinstance(value, Number)
False
>>> isinstance(1, Number)
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM