我不明白这个问题。
有两种语义截然不同的东西被当作“替代品”。
类型转换是一回事。它适用于任何支持 的对象,__float__
可以是各种各样的对象,其中很少有实际是数字的。
try:
myinput = float(input)
except:
raise ValueError("input is not a well-formed number")
# at this point, input may not be numeric at all
# it may, however, have produced a numeric value
类型测试是另一回事。这仅适用于作为特定类集的正确实例的对象。
isinstance(input, (float, int, long) )
# at this point, input is one of a known list of numeric types
这是响应的示例类float
,但仍然不是数字。
class MyStrangeThing( object ):
def __init__( self, aString ):
# Some fancy parsing
def __float__( self ):
# extract some numeric value from my thing
“实数(整数或浮点数)”这个问题通常是无关紧要的。许多东西是“数字”的,可以在数字运算中使用,但不是整数或浮点数。例如,您可能已经下载或创建了一个有理数包。
There's no point in overvalidating inputs, unless you have an algorithm that will not work with some types. These are rare, but some calculations require integers, specifically so they can do integer division and remainder operations. For those, you might want to assert that your values are ints.