检查 python 对象是否可以解释为实数 [python]

checking if python object can be interpreted as real number [python]

我把函数写在了python:

def is_number_like(x):
     try:
        int(x) + 1
    except:
        return False
    return True

float(x)int(x)有区别吗?或者 + 1 部分在某些情况下有用吗?

编辑:is_number_like 将在传递字符串时 return True - 这是我不想成为的。我想要一个函数,它会在任何时候将类似文本的值作为参数传递 return False 。有方法吗?

也许:

def is_number_like(x):
     try:
        x + 1
    except:
        return False
    return True

会好些吗?

或者也许:

def is_number_like(x):
     try:
        float(x + 1) == float(x) + 1
    except:
        return False
    return True

我想编写一个模块,它可以接受任何代表一维实数的行为良好的数字类型(例如 SimpleITK.sitkUInt8 数字类型或 numpy.int32 等等...)。

恐怕会有库在转换为 int 或 float 时不会抛出错误。例如我可以想象这样的情况:

>>> z = SomeComplexType(1. + 2.j)
>>> z
(1+2j)
>>> z -= 2.j
>>> z
(1+0j)
>>> float(z) # does not raise an error
1.

这可能吗,我应该担心这种情况吗?

是否所有设计良好的实数类型都可以毫无错误地转换为 float

ps。我已经读过这个: How do I check if a string is a number (float)?

float(..)int(..)有区别。

float(..) 将尝试解析 string 或任何具有 __float__ 方法的对象。例如 intfloatcomplex 有一个 __float__ 方法 。您也可以为自定义 class 定义此类方法。

如果您打算将复数转换为 float(..),则会出现错误:

>>> float(2+2j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float

float(..)函数的结果保证是float:如果__float__方法return是一个非浮点值,它将 引发 TypeError:

>>> class Foo:
...     def __float__(self):
...         return 2j
... 
>>> float(Foo())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __float__ returned non-float (type complex)

所以简单的 float(..) 尝试就足够了:

def is_number_like(x):
     try:
        float(x)
        return True
    except TypeError, ValueError:
        return False

大多数类数字类型Python(如numpy.int16)**支持这样的__float__方法。

另一方面,

int(..) 使用 string 和 __int__ 方法 。同样,如果您调用 int(..),结果保证是 int.

因此在 中,您可以使用两项检查:一项针对 float(..),一项针对 int(..)

def is_number_like(x):
     try:
        int(x)
        return True
    except TypeError, ValueError:
        try:
            float(x)
            return True
        except TypeError, ValueError:
            return False

或者如果你想 return 类似数字的对象:

def is_number_like(x):
     try:
        return int(x)
    except TypeError:
        try:
            return float(x)
        except TypeError:
            return None

(如果两次尝试都失败,这将 return None)。

请注意,在 中,还有一个 long 类型(你猜怎么着,它适用于 __long__)。

在 python 中,复数不能直接转换为 int 或 float,这会引发 TypeError: can't convert complex to...

除 "int or float convertible" 之外的任何其他对象都会引发 ValueError

要根据自定义 class "convertible" 制作对象,必须定义适当的 "dunders" __int____float__see doc

所以一个检查对象是否可以转换为实数的函数你可以这样做:

def is_real_number(number):
    try:
        int(number)
    except TypeError, ValueError:
        return False
    return True

为什么不直接使用

any([isinstance(x, t) for t in [float, int, complex]])

您可以根据需要修改类型列表。

如果我没理解错的话,你实际上想做的是找出一个对象是否以类似 "number" 的方式运行(例如,你能否将 +1 附加到它)。如果是这样,还有一个更简单的方法:

>>> from numbers import Number
>>> 
>>> my_complex_number = 3-2j
>>> my_stringy_number = "3.14"
>>>
>>> isinstance(my_complex_number, Number)
True
>>> isinstance(my_stringy_number, Number)
False