The reason is that prior to inititalizer, that is __init__
function, a constructor, that is __new__
, is called. It is called with the same arguments as __init__
. As for your class it is not defined, it's superclass' one, that is float
's, is called, and error is raised. You can see it if you wrap constructor:
>>> 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
If you want add custom attributes, use something like follows:
>>> 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')