我查看了在Python3.8中实现的新特性,发现了一个新函数numerator, denominator = x.as_integer_ratio()
。他们在文件中声明:
Return a pair of integers whose ratio is exactly equal to the original integer and with a positive denominator. The integer ratio of integers (whole numbers) is always the integer as the numerator and 1 as the denominator.
基本上是这个代码
x = 10
numerator, denominator = x.as_integer_ratio()
print(numerator)
print(denominator)
输出
10
1
我只是想知道拥有一个总是返回相同值和1的函数有什么意义?我还看到它以前在float
上可用,这是有道理的
从docs
这个较小的API扩展使得可以将分子、分母=x.写为_integer_ratio(),并使其跨多个数字类型工作
这种方法已经在几种类型上可用,例如
float
。现在,使用此方法的代码可以处理更多类型。把它归档在duck-typing下考虑一个函数,该函数取一个参数并将其作为分数操作:
在3.8之前,我们只能将其称为浮点数:
但现在我们可以用int来调用它,并获得可靠的行为:
改变的主要原因似乎是为了实现一致性,并为mypy键入,以便
int
可以是float
的子类型深入到pipermail中,它似乎有助于通过分解等方式更改类型的域:
见:
相关问题 更多 >
编程相关推荐