【发布时间】:2012-11-12 03:15:59
【问题描述】:
python 文档here 中的以下示例让我有些困惑。
>>> class inch(float):
... "Convert from inch to meter"
... def __new__(cls, arg=0.0):
... return float.__new__(cls, arg*0.0254)
...
>>> print inch(12)
0.3048
>>>
据推测,float 是在 Python 深处定义的实际浮点类。当我们调用float.__new__(cls, argument) 时,我们偷偷地调用了为给定参数返回float 实例的函数,但是我们传递给它的是inch 类而不是float 类。既然英寸类并没有真正做任何事情,为什么这会起作用?
【问题讨论】:
标签: python