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

如何在Python中实现强类型整数?解决NewType运行时等价问题

解决NewType运行时相等判断问题的方案

你说得对,NewType只在静态类型检查时生效,运行时本质还是原始类型,所以A(1) == B(1)会返回True。要让这个判断返回False,有几种比dataclass更高效的实现方式:

方案1:继承int并重写__eq__(推荐,性能接近原生int)

之前你尝试继承int没成功,是因为没重写__eq__方法——默认的int相等判断只比较数值,不检查类型。重写后就能同时校验类型和数值:

class A(int):
    def __eq__(self, other):
        # 只有对方是A类型且数值相等时才返回True
        return isinstance(other, A) and super().__eq__(other)

class B(int):
    def __eq__(self, other):
        return isinstance(other, B) and super().__eq__(other)

print(A(1) == B(1))  # 输出False
print(A(1) == A(1))  # 输出True

这个方案的优势是:

  • 性能几乎和原生int一致,没有dataclass的额外开销
  • 自动继承int的所有方法(比如加减乘除、位运算等),不需要手动实现转发函数
  • 静态类型检查依然有效,编辑器能识别这是不同的类型

方案2:自定义轻量包装类(灵活性高)

如果不需要和int兼容,只需要存储值并做类型敏感的相等判断,可以写极简的包装类,只实现必要的方法:

class A:
    __slots__ = ("value",)  # 用__slots__减少内存开销,提升性能
    def __init__(self, value: int):
        self.value = value

    def __eq__(self, other):
        return isinstance(other, A) and self.value == other.value

    def __repr__(self):
        return f"A({self.value})"

class B:
    __slots__ = ("value",)
    def __init__(self, value: int):
        self.value = value

    def __eq__(self, other):
        return isinstance(other, B) and self.value == other.value

print(A(1) == B(1))  # 输出False

加上__slots__后,这个类的内存占用和性能会比dataclass好很多,适合不需要和int交互的场景。

对比dataclass方案

你当前的dataclass方案确实能实现需求,但会自动生成大量额外方法(比如__hash__、__lt__、__gt__等),如果只需要相等判断,这些都是不必要的开销。除非你需要dataclass的序列化、自动生成repr等特性,否则上面两种方案更高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:24:42