分数对象没有__int__但int(分数(...))仍然有效 [英] Fraction object doesn't have __int__ but int(Fraction(...)) still works

查看:143
本文介绍了分数对象没有__int__但int(分数(...))仍然有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,当你有一个对象时,可以使用 int 函数将其转换为整数。

In Python, when you have an object you can convert it to an integer using the int function.

例如 int(1.3)将返回 1 。这通过使用对象的 __ int __ 魔术方法在内部工作,在这种特殊情况下 float .__ int __

For example int(1.3) will return 1. This works internally by using the __int__ magic method of the object, in this particular case float.__int__.

在Python中分数对象可用于构造精确分数。

In Python Fraction objects can be used to construct exact fractions.

from fractions import Fraction
x = Fraction(4, 3)

分数对象缺少 __ int __ 方法,但你仍然可以调用 int ()在它们上面并得到一个合理的整数。我想知道如果没有定义 __ int __ 方法,这是怎么可能的。

Fraction objects lack an __int__ method, but you can still call int() on them and get a sensible integer back. I was wondering how this was possible with no __int__ method being defined.

In [38]: x = Fraction(4, 3)

In [39]: int(x)
Out[39]: 1


推荐答案

使用 __ trunc __ 方法。

>>> class X(object):
    def __trunc__(self):
        return 2.


>>> int(X())
2

__ float __ 无法使用

>>> class X(object):
    def __float__(self):
        return 2.

>>> int(X())
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    int(X())
TypeError: int() argument must be a string, a bytes-like object or a number, not 'X'

CPython源显示何时使用 __ trunc __

这篇关于分数对象没有__int__但int(分数(...))仍然有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆