Python 中自定义 类 的字符串格式
String formatting for custom classes in Python
我编写了自定义 class IntegerMod
整数模素数。一切正常。然后将它们用作用 numpy.poly1d
构建的多项式的系数,并设法在 IntegerMod
中实现足够的方法,以便使用这些多项式的操作按我的需要工作(例如,找到给定一堆点的插值多项式) .
只剩下一点细节,那就是 print(pol)
对于那些多项式实际上是失败的,因为 Python 试图对系数使用字符串格式 %g
,并且没有说 IntegerMod
应该是字符串或数字。
其实IntegerMod
继承自numbers.Number
,但似乎还不够。我的问题是,我可以在 class 中实现字符串格式化行为吗?如果没有,我应该如何处理这个问题?
产生错误的 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 格式需要浮点数。
像这样
def __float__(self):
return float(self.k)
我编写了自定义 class IntegerMod
整数模素数。一切正常。然后将它们用作用 numpy.poly1d
构建的多项式的系数,并设法在 IntegerMod
中实现足够的方法,以便使用这些多项式的操作按我的需要工作(例如,找到给定一堆点的插值多项式) .
只剩下一点细节,那就是 print(pol)
对于那些多项式实际上是失败的,因为 Python 试图对系数使用字符串格式 %g
,并且没有说 IntegerMod
应该是字符串或数字。
其实IntegerMod
继承自numbers.Number
,但似乎还不够。我的问题是,我可以在 class 中实现字符串格式化行为吗?如果没有,我应该如何处理这个问题?
产生错误的 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 格式需要浮点数。
像这样
def __float__(self):
return float(self.k)