Python: Why do int.numerator and int.denominator exist?

核能气质少年 提交于 2020-06-11 16:16:15

问题


int.numerator and int.denominator are a mystery to me.

help(int.numerator) states:

the numerator of a rational number in lowest terms

But as far as I know, int is not a rational number. So why do these properties exist?


回答1:


See http://docs.python.org/library/numbers.html - int (numbers.Integral) is a subtype of numbers.Rational.

>>> import numbers
>>> isinstance(1337, numbers.Integral)
True
>>> isinstance(1337, numbers.Rational)
True
>>> issubclass(numbers.Integral, numbers.Rational)
True

The denominator of an int is always 1 while its numerator is the value itself.

In PEP 3141 you find details about the implementation of the various number types, e.g. proving the previous statement:

@property
def numerator(self):
    """Integers are their own numerators."""
    return +self

@property
def denominator(self):
    """Integers have a denominator of 1."""
    return 1


来源:https://stackoverflow.com/questions/10156777/python-why-do-int-numerator-and-int-denominator-exist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!