[Tutor] Python Question - Repeating output. [defining special methods]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 10 Jun 2002 15:28:28 -0700 (PDT)


> The math like equality test that you are used to is performed in Python
> with the double equal:
>
> a == a + 1
>
> which is always false as you would expect because mathematically it's
> nonsensical!



That is, unless we're working in modulo arithmetic;

###
class ModNumber:
    def __init__(self, n, m):
        self.n, self.m = n % m, m

    def __add__(self, other):
        return ModNumber((self.n + other.n), self.m)

    def __str__(self):
        return "%s modulo %s" % (self.n, self.m)

    def __coerce__(self, other):
        if type(other) == type(42):
            return (self, ModNumber(other, self.m))

    def __eq__(self, other):
        return (self.n, self.m) == (other.n, other.m)
###


"Modulo arithmetic" wraps around a particular modulus, just as a clock's
hands wrap around twelve.  Here's an example of this modulo "clock"
arithmetic:


###
>>> print ModNumber(5, 12) + 9
2 modulo 12               ## Nine hours after six o'clock is
                          ## three o'clock.  We have to account
                          ## for the fact that humans count by one,
                          ## not zero.
>>> ModNumber(0, 1) == ModNumber(0, 1) + 1
1
###


I'm sorry, I just couldn't resist.  *grin*