class float([x])
将数字或数字的字符串表示形式转换为与它等效的有符号浮点数。
说明
如果参数 x 是一个字符串,则 x 应该是一个十进制数字的字符串表示形式,数字前面可以添加符号 +
(表示正数)、-
(表示负数),符号和数字之间不能出现空格,但是符号前面和数字后面允许出现空格。
>>> float('0xf')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '0xf'
>>> float('3.14159')
3.14159
>>> float('-3.14159')
-3.14159
>>> float('- 3.14159')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '- 3.14159'
>>> float(' -3.14159 ')
-3.14159
>>> float(' +3.14159 ')
3.14159
如果参数 x 是一个整数或是一个浮点数,则返回与它等效的浮点数;如果 x 超出了 float 类型的范围,则引发 OverflowError 错误。
>>> float(3)
3.0
>>> float(-3)
-3.0
>>> float(3.14159)
3.14159
>>> float(-3.14159)
-3.14159
如果参数 x 缺省,则返回 0.0
,
>>> float()
0.0
如果参数 x 是普通的Python对象,float([x]) 返回的是调用 x .__ float __()
结果。
示例
>>> class A:
... def __init__(self, score):
... self.score = score
...
>>> a = A(98)
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: float() argument must be a string or a number, not 'A'
>>>
>>> class A:
... def __init__(self, score):
... self.score = score
... def __float__(self):
... return self.score
...
>>> a = A(98)
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: A.__float__ returned non-float (type int)
>>> a = A(98.0)
>>> float(a)
98.0
>>>
网友评论