wha*_*ven 5 python int truncate python-3.x
trunc和int函数为我尝试过的每个浮点类型输入返回相同的输出.
它们的不同之处在于int它们也可用于将数字字符串转换为整数.
所以我有一个双重问题:
我想知道,除了字符串之外,是否有任何输入trunc并int给出不同的输出?
如果没有,何时trunc用于将浮点型数转换为整数更好?
int并math.trunc有一个有点类似关系str和repr.int委托类型的__int__方法,__trunc__如果__int__找不到则返回到方法.直接math.trunc委托类型的__trunc__方法,没有后备.不同于__str__和__repr__,它们总是被定义为object两者,int并且math.trunc可以提出开箱即用的错误.
对于所有的内置类型,我知道,两者__int__并__trunc__以理智的定义在适当情况下.但是,您可以定义自己的一组测试类,以查看您获得的错误:
class A:
def __int__(self):
return 1
class B:
def __trunc__(self):
return 1
class C(): pass
Run Code Online (Sandbox Code Playgroud)
math.trunc(A())并且math.trunc(C())都会提高TypeError: type X doesn't define __trunc__ method.int(C())会提高TypeError: int() argument must be a string, a bytes-like object or a number, not 'C'.然而int(A()),int(B())并且math.trunc(B())将全部成功.
最后决定使用哪种方法是内涵之一.trunc本质上是一个类似的数学运算floor,虽然int是一个通用的转换,并且在更多的情况下成功.
并且不要忘记operator.index和__index__方法.
| 归档时间: |
|
| 查看次数: |
348 次 |
| 最近记录: |