我IntegerMod為整數(shù)模一個(gè)素?cái)?shù)編寫了一個(gè)自定義類。一切正常。然后將它們用作用 構(gòu)建的多項(xiàng)式的系數(shù)numpy.poly1d,并設(shè)法實(shí)現(xiàn)足夠的方法,IntegerMod以便對(duì)這些多項(xiàng)式的操作按我的需要工作(例如,找到給定一堆點(diǎn)的插值多項(xiàng)式)。只剩下一點(diǎn)細(xì)節(jié),那就是print(pol)那些多項(xiàng)式實(shí)際上失敗了,因?yàn)?Python 嘗試對(duì)%g系數(shù)使用字符串格式,但未能說(shuō)明IntegerMod應(yīng)該是字符串還是數(shù)字。實(shí)際上IntegerMod繼承自numbers.Number,但似乎還不夠。我的問(wèn)題是,我可以在我的班級(jí)中實(shí)現(xiàn)字符串格式的行為嗎?如果沒(méi)有,我應(yīng)該如何處理這個(gè)問(wèn)題?產(chǎn)生錯(cuò)誤的 MWE:import numbersimport numpy as npclass 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' """
1 回答

青春有我
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
也許您應(yīng)該實(shí)現(xiàn)該__float__
方法,因?yàn)?poly1d 格式需要浮點(diǎn)數(shù)。
像這樣的東西
def __float__(self): return float(self.k)
添加回答
舉報(bào)
0/150
提交
取消