初始化float的子类时出错

时间:2013-12-19 21:05:28

标签: python inheritance python-2.7 built-in

这就是我正在做的事情:

class D(float):
    def __init__(self, name):
        self._name = name
        print name

但是当我尝试初始化D类型的对象时:

d = D('aaa')

我收到此错误:

Traceback (most recent call last):
  File "/home/user/untitled1.py", line 22, in <module>
    d = D('aaa')
ValueError: could not convert string to float: aaa

为什么呢?我没有初始化一个浮点数,只是设置一个名字。我没有调用浮动的__init__

1 个答案:

答案 0 :(得分:2)

原因是在启动程序之前,即__init__函数,调用构造函数__new__。它的调用与__init__相同。至于你的类,它没有被定义,它的超类'one,即float被调用,并且引发了错误。如果你包装构造函数,你可以看到它:

>>> class D(float):
...     def __new__(cls, *args, **kwargs):
...         print cls, args, kwargs
...         return super(D, cls).__new__(cls, *args, **kwargs)
...     def __init__(self, value):
...         print value
...
>>> D('a')
<class '__main__.D'> ('a',) {}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __new__
ValueError: could not convert string to float: a

如果要添加自定义属性,请使用以下内容:

>>> class D(float):
...     __slots__ = ['name']
...     def __new__(cls, *args, **kwargs):
...         name = kwargs.pop('name')
...         obj = super(D, cls).__new__(cls, *args, **kwargs)
...         obj.name = name
...         return obj
...
>>> d = D(0, name='d')
>>> e = D(1, name='e')
>>> d, d.name
(0.0, 'd')
>>> e, e.name
(1.0, 'e')