gpt4 book ai didi

python - 在 Python 3 中,如何创建类似数字的对象?

转载 作者:太空宇宙 更新时间:2023-11-04 08:59:54 24 4
gpt4 key购买 nike

我想将一个数字(intfloat 等)及其科学记数法(包括它的精度)存储到一个对象中。

例如,我将 a = 0.001 作为它的值,并将 1.0e-3 作为它的科学记数法。目前我有一个类:

def numLike():
def __init__(self, n, p):
self.n = n
self.p = p

a = numLike(0.001, '1.0e-3')

这样我至少可以将这两个值关联到 1 个对象中。当我想进行计算时,我将使用 a.n,当打印出来时使用 a.p

我想实现的是Python在计算时将a识别为a.n,将a识别为a.p 当不涉及计算时。所以当我输入a + 0.003时,它应该给我0.004,当我输入a时它返回'1.0e-3 ' 自动。

最佳答案

无需存储字符串表示,只在需要时生成:扩展float并覆盖__str__:

class x(float):
def __str__(self):
return "{:e}".format(self)

print (float(101)) # 101.0
print (x(101)) # 1.010000e+02

或者,为了传递精度,

class x(float):
def __new__(cls, value, prec=6):
self = float.__new__(cls, value)
self.prec = prec
return self

def __str__(self):
return "{:.{}e}".format(self, self.prec)

print (float(101)) # 101.0
print (x(101)) # 1.010000e+02
print (x(101, 2)) # 1.01e+02

如果您决定按自己的方式行事,则必须覆盖所有算术(__add__ 和 friend )并将其委托(delegate)给 self.n

关于python - 在 Python 3 中,如何创建类似数字的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26502396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com