Python: Why do int.numerator and int.denominator e

2020-08-09 09:09发布

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?

标签: python math int
1条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-08-09 09:21

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
查看更多
登录 后发表回答