在 python 中使用 `round` 与 `__round__` 有什么不同?
What is the different in the use of `round` vs. `__round__` in python?
在 python 3 中有效:
Celsius = [39.2, 45.2, 37.3, 37.8, 89]
Fahrenheit = map(lambda x: ((float(9/5))*x + 32).__round__(3), Celsius)
print(list(Fahrenheit))
[102.56, 113.36, 99.14, 100.04, 192.2]
但是,这不起作用,为什么?:
Fahrenheit = map(lambda x: ((float(9/5))*x + 32).round(3), Celsius)
此外,现在很多 python 脚本不使用这种旧格式 __round__
,我认为是为了让脚本看起来更干净。还有其他核心原因吗?
没有float.round()
方法,没有。您将改用 round()
function,传递您的值和要舍入的位数。
round()
是一个函数,因为舍入是一种适用于所有数字类型的运算,而不仅仅是浮点数。就像 len()
适用于所有序列(不仅仅是 list
或 tuple
或 str
),而 str
适用于所有 Python 对象。
像所有 __*__
dunder 方法一样,__round__
is a hook 用于自定义 classes 以覆盖 class 的舍入方式。 round()
函数在生成输出时使用它,其他一些功能也是如此。
这个有效:
Fahrenheit = map(lambda x: round((9.0/5) * x + 32, 3), Celsius)
注意我这里没有用float(9/5)
!在 Python 两个中,那就是 1.0:
>>> float(9/5)
1.0
因为9/5
是先使用整数除法计算的。 9.0/5
使用浮点除法(因为至少有一个操作数是浮点值),所以给你正确的商:
>>> 9.0/5
1.8
您在这里使用 Python 3,其中 /
表示真正的除法(即使对于整数操作数也产生浮点数),但是 float()
调用在那里仍然只是多余的。
在 python 3 中有效:
Celsius = [39.2, 45.2, 37.3, 37.8, 89]
Fahrenheit = map(lambda x: ((float(9/5))*x + 32).__round__(3), Celsius)
print(list(Fahrenheit))
[102.56, 113.36, 99.14, 100.04, 192.2]
但是,这不起作用,为什么?:
Fahrenheit = map(lambda x: ((float(9/5))*x + 32).round(3), Celsius)
此外,现在很多 python 脚本不使用这种旧格式 __round__
,我认为是为了让脚本看起来更干净。还有其他核心原因吗?
没有float.round()
方法,没有。您将改用 round()
function,传递您的值和要舍入的位数。
round()
是一个函数,因为舍入是一种适用于所有数字类型的运算,而不仅仅是浮点数。就像 len()
适用于所有序列(不仅仅是 list
或 tuple
或 str
),而 str
适用于所有 Python 对象。
像所有 __*__
dunder 方法一样,__round__
is a hook 用于自定义 classes 以覆盖 class 的舍入方式。 round()
函数在生成输出时使用它,其他一些功能也是如此。
这个有效:
Fahrenheit = map(lambda x: round((9.0/5) * x + 32, 3), Celsius)
注意我这里没有用float(9/5)
!在 Python 两个中,那就是 1.0:
>>> float(9/5)
1.0
因为9/5
是先使用整数除法计算的。 9.0/5
使用浮点除法(因为至少有一个操作数是浮点值),所以给你正确的商:
>>> 9.0/5
1.8
您在这里使用 Python 3,其中 /
表示真正的除法(即使对于整数操作数也产生浮点数),但是 float()
调用在那里仍然只是多余的。