Search code examples
pythonoopstring-formatting

String formatting for custom classes in Python


I coded a custom class IntegerMod for integers modulo a prime number. Everything works fine. Then used them as coefficients of polynomials built with numpy.poly1d, and managed to implement enough methods in IntegerMod so that operations with those polynomials work as I needed (for instance, finding interpolating polynomials given a bunch of points).

Just a little detail remains, it is that print(pol) for those polynomials actually fails, because Python tries to use string formating %g for the coefficents, and that fails saying IntegerMod should be a string or a number. In fact IntegerMod inherits from numbers.Number, but it seems not enough. My question is, can I implement in my class the behaviour for string formatting? If not, how should I deal with this issue?

A MWE producing the error:

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'
    """

Solution

  • Maybe you should implement the __float__ method, since poly1d formatting expects floats.

    Something like this

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