如何使自定义Number类可转换为int&浮动?

时间:2012-07-12 00:46:31

标签: python python-3.x numbers

我在python 3中实现了一个数字类。我需要做什么呢

float(mynumber)

工作正常吗?

2 个答案:

答案 0 :(得分:7)

来自文档,Emulating Numeric Types

object.__complex__(self) 
object.__int__(self) 
object.__long__(self) 
object.__float__(self) 

Called to implement the built-in functions complex(), int(), long(), and float(). 
Should return a value of the appropriate type.

答案 1 :(得分:2)

实施__float____int__或您想要的任何内容......

还值得注意的是,使用abcnumbers模块对最终用户有用...另请参阅:http://www.rafekettler.com/magicmethods.html下"类型转换魔术方法"