Python中自定义类的字符串格式
我为素数模整数编写了一个自定义类Python中自定义类的字符串格式,python,oop,string-formatting,Python,Oop,String Formatting,我为素数模整数编写了一个自定义类IntegerMod。一切正常。然后将它们用作使用numpy.poly1d构建的多项式的系数,并设法在IntegerMod中实现足够多的方法,以便根据需要使用这些多项式进行操作(例如,查找给定一组点的插值多项式) 只剩下一点细节,就是那些多项式的print(pol)实际上失败了,因为Python尝试对系数使用字符串格式化%g,并且没有说IntegerMod应该是字符串或数字。 事实上,IntegerMod继承自numbers.Number,但似乎还不够。我的问题是
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'
"""
导入编号
将numpy作为np导入
类IntegerMod(Number.Number):
定义初始值(self,k,p):
self.k=k%p
self.p=p
定义报告(自我):
返回“”%(self.k,self.p)
如果名称=“\uuuuu main\uuuuuuuu”:
p=13
coef1=整数模(2,p)
coef2=整数模(4,p)
打印(coef1)#按预期工作
pol=np.poly1d([coef1,coef2])
印刷品(pol)
“”错误:
s='%.4g'%q
TypeError:float()参数必须是字符串或数字,而不是“IntegerMod”
"""
也许您应该实现\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
像这样的
def __float__(self):
return float(self.k)
为什么不实现str方法(请记住,当str_uu丢失时,print和任何使用str()的函数调用uuu repr_uuu())将更改为np.poly1d([repr(coef1),repr(coef2)]
以获取\uu repr_uuu
。