Python: Can a subclass of float take extra arguments in its constructor?
As float is immutable you have to overwrite __new__
as well. The following should do what you want:
class Foo(float):
def __new__(self, value, extra):
return float.__new__(self, value)
def __init__(self, value, extra):
float.__init__(value)
self.extra = extra
foo = Foo(1,2)
print(str(foo))
1.0
print(str(foo.extra))
2
See also Sub-classing float type in Python, fails to catch exception in __init__()
Both @cgogolin and @qvpham provide working answers. However, I reckon that float.__init__(value)
within the __init__
method is irrelevant to the initialization of Foo
. That is, it does nothing to initialize attributes of Foo
. As such, it rather causes confusion on the necessity of the operation toward subclassing the float
type.
Indeed, the solution can be further simplified as follows:
In [1]: class Foo(float):
...: def __new__(cls, value, extra):
...: return super().__new__(cls, value)
...: def __init__(self, value, extra):
...: self.extra = extra
In [2]: foo = Foo(1,2)
...: print(str(foo))
1.0
In [3]: print(foo.extra)
2