gpt4 book ai didi

python - Python 中自定义类的字符串格式

转载 作者:太空宇宙 更新时间:2023-11-03 15:36:32 24 4
gpt4 key购买 nike

我为整数模素数编写了一个自定义类 IntegerMod。一切正常。然后将它们用作使用 numpy.poly1d 构建的多项式的系数,并设法在 IntegerMod 中实现足够的方法,以便使用这些多项式的操作按我的需要工作(例如,找到给定一堆点的插值多项​​式)。

只剩下一个小细节,就是那些多项式的 print(pol) 实际上失败了,因为 Python 尝试对系数使用字符串格式 %g,并且未能说明 IntegerMod 应该是字符串或数字。其实IntegerMod继承自numbers.Number,但似乎还不够。我的问题是,我可以在类里面实现字符串格式化的行为吗?如果没有,我应该如何处理这个问题?

产生错误的 MWE:

import numbers
import numpy as np


class IntegerMod(numbers.Number):
def __init__(self, k, p):
self.k = k % p
self.p = p

def __repr__(self):
return "<%d (%d)>" % (self.k, self.p)

if __name__ == "__main__":
p = 13
coef1 = IntegerMod(2, p)
coef2 = IntegerMod(4, p)
print(coef1) # Works as expected
pol = np.poly1d([coef1, coef2])
print(pol)
""" # error:
s = '%.4g' % q
TypeError: float() argument must be a string or a number, not 'IntegerMod'
"""

最佳答案

也许您应该实现 __float__ 方法,因为 poly1d 格式需要 float 。

像这样

    def __float__(self):
return float(self.k)

关于python - Python 中自定义类的字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54479829/

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