Python:float 的子类可以在其构造函数中使用额外的参数吗?

标签 python python-3.x types subclass built-in

在 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/

相关文章:

python - 如何正确删除 Scikit-Learn 的 DPGMM 的冗余组件?

python - 删除 python 字典中的一个级别,保留值

python - 使用正则表达式和 python 3 在字符串中查找模式

c++ - C/C++ 中字符的大小 ('a' )

python - Django REST UnitTest 没有提交文件

Python正则表达式查找两个子字符串之间的所有字符串

python - 将累积和最大值分配给数据点分组

python-3.x - 使用 Python 加密文本 - RaspberryPi Org 项目

c++函数返回模板类型检查

types - 有没有办法检测卡的类型是借记卡还是信用卡