You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何子类化mpmath的mpf类型?常规继承报错的可行方案

如何正确继承mpmath的mpf类型

mpmath的mpf并非普通Python类,它的实例构造逻辑在__new__方法而非__init__,直接重写__init__会触发object.__init__()的参数错误。以下两种方案可以实现对mpf的扩展:

方案一:重写__new__方法继承mpf

对于数值类这类不可变类型,实例的创建由__new__负责,只需重写该方法即可完成继承:

import mpmath

class A(mpmath.mpf):
    def __new__(cls, v):
        # 调用父类的__new__创建实例
        return super().__new__(cls, v)
    
    # 添加自定义方法示例
    def multiply_by_three(self):
        return self * 3

测试代码:

a = A(2)
print(a)  # 输出 2.0
print(a.multiply_by_three())  # 输出 6.0

方案二:使用组合方式封装mpf

如果需要更灵活的扩展逻辑,避免直接继承底层类型的限制,可以通过封装mpf实例实现:

import mpmath
import math

class A:
    def __init__(self, v):
        self._mpf = mpmath.mpf(v)
    
    # 重载运算符,让类表现得和mpf一致
    def __add__(self, other):
        if isinstance(other, A):
            return A(self._mpf + other._mpf)
        return A(self._mpf + other)
    
    def __sub__(self, other):
        if isinstance(other, A):
            return A(self._mpf - other._mpf)
        return A(self._mpf - other)
    
    # 自定义方法示例
    def get_decimal_digits(self):
        # 返回当前精度对应的十进制位数
        return int(self._mpf.prec * math.log10(2))
    
    # 重写repr,保持输出和mpf一致
    def __repr__(self):
        return repr(self._mpf)

测试代码:

a = A(10)
b = A(4)
print(a - b)  # 输出 6.0
print(a.get_decimal_digits())  # 输出约15(默认精度下)

错误原因说明

mpf作为特殊数值类型,其初始化过程不依赖__init__方法,当你在自定义类中调用super().__init__(v)时,实际调用的是object.__init__,而该方法仅接受实例本身作为参数,因此触发TypeError。

内容的提问来源于stack exchange,提问作者tr7r

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 16:43:18