首页 > 解决方案 > 使用 json.dumps() 创建 int 的子类,意外行为

问题描述

我正在尝试创建一个int打印为字符串的子类,但仍可用作数学变量。

这是我到目前为止所拥有的:

class xint(int):

    def __new__(self, value):
        self.value = value
        return super(xint, self).__new__(self)

    def __str__(self):
        return f"'{self.value}'"
    __repr__ = __str__

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

使用这个我可以做到:

x = xint(2)
x = [x]
print(x)
>> ['2']

这就是我想要的行为。但我遇到的问题是,如果我尝试将此列表转换为 JSON 字符串,那么['2']我得到的不是[0].

import json

x = xint(2)
x = [x]
x = json.dumps(x)
print(x)
>> [0]

__repr__除了and之外,我还缺少一些方法来解决这个问题__str__吗?

标签: pythonjson

解决方案


这个例子修正了你的错误,但它并没有解决你的问题:

import json


class Xint(int):
    def __str__(self):
        return f"'{int(self)}'"

    # I'm leaving this in, but I think it's wrong
    # a representation like f'Xint({int(self)})' would be better
    __repr__ = __str__


x = Xint(2)
y = [x]
print(x, y)
print(json.dumps(y))

结果:

'2' ['2']
[2]

请注意json.dumps()现在如何正确显示您的2. 但它仍然没有像那样显示引号print()。这是因为json识别出它被要求转储的变量的类型,它只是一个int.

如果你需要这个,你需要说服json它真的只是一个字符串,或者是某种json可以作为字符串添加到转储中的类型。但这几乎会破坏您可能为您的类型考虑的所有其他用途。

我认为真正的问题是这里的 XY 问题。与其问如何使您的解决方案发挥作用,也许您可​​以分享您尝试用新类型解决的问题?


推荐阅读