python - 使用 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__
吗?
解决方案
这个例子修正了你的错误,但它并没有解决你的问题:
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 问题。与其问如何使您的解决方案发挥作用,也许您可以分享您尝试用新类型解决的问题?
推荐阅读
- scala - 可选分页
- python - 如果语句问题打印所有短语
- cuckoo - 没有pip2怎么下载
- mysql - 如何根据具有特定值的字段逐行递增 id
- list - 从 Firestore Flutter 中读取子集合
- javascript - React.memo 不适用于功能组件。如果我所看到的不支持该功能,那么优化的另一种方法是什么?
- python - OpenCV Python:如何将图像叠加到另一个图像的中心
- c# - Asp.net core 3.0 在发布或构建时发布视图文件 (.cshtml)
- sql - 这段代码是什么意思..[select @a:=password(?)]
- javascript - 如何在从另一个页面加载的模式中运行脚本?