在 Python 3.4 中,我想创建一个 float
的子类——它可以像 float
一样用于数学和 bool 运算,但还有其他的自定义功能,并且可以在初始化时接收控制该功能的参数。 (具体来说,我想要一个自定义的 __str__
和一个在该方法中使用的参数。)
但是,我似乎无法让 float
的子类具有功能性的双参数构造函数。为什么?这仅仅是对扩展内置类型的限制吗?
例子:
class Foo(float):
def __init__(self, value, extra):
super().__init__(value)
self.extra = extra
现在,如果我尝试 Foo(1,2)
,我会得到:
TypeError: float() takes at most 1 argument (2 given)
令人惊讶的是,我的新 __init__
参数也被强制执行,所以如果我执行 Foo(1)
我得到:
TypeError: __init__() missing 1 required positional argument: 'extra'
这是怎么回事?我对 list
的子类型做了类似的事情,但很惊讶它在 float
上不起作用。
最佳答案
由于 float 是不可变的,因此您还必须覆盖 __new__
。以下应该做你想做的:
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
另见 Sub-classing float type in Python, fails to catch exception in __init__()
关于Python:float 的子类可以在其构造函数中使用额外的参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35943789/