[Tutor] How to introduce OO?

Kirby Urner urnerk@qwest.net
Thu, 06 Dec 2001 08:14:15 -0800


> > Perhaps I asked the wrong question.  If all I want is to use
> > Python for a scripting language and some simple programs,
> > is OOP perhaps overkill?

At 02:41 PM 12/6/2001 +0000, alan.gauld@bt.com replied:

>Definitely.

I like to introduce Python's OO with operator overriding,
as here's something you can do with objects that you
simply cannot do procedurally.

Suppose I want numbers that, when multiplied together,
return a*b mod n, i.e. the remainder of the product a*b,
after being divided by some modulus n.

   class Modno:

         def __init__(self,val,mod):
            self.value = val
            self.mod = mod

         def __mul__(self,other):
            product = (self.value * other.value) % self.mod
            return Modno(product,self.mod)

        def __repr__(self):
            return str(self.value)


  >>> from play import Modno

  >>> a = Modno(4,5)
  >>> b = Modno(3,5)
  >>> a*b
  2
  >>> c=a*b       # a*b returns a Modno, usable right away
  >>> c*c*c*c     # using c, a Modno, returned by a*b
  1

Of course you can write a modmul procedure that takes
ordinary integers a,b and returns the product mod some
global n.  But you don't get to use * (multiplication
symbol) as a binary operator.

I then enhance the above class with __add__ which works
the same way:  returns (a + b) mod n.  Then add a __pow__
so you can exponentiate c (c**4 instead of c*c*c*c).
Then add __div__...  lotsa fun.

More code to ensure val<mod, only integers, a,b have
same mod before multiplying etc. etc. is optional.

None of this is entirely trivial in the sense of "without
application".  Learning some modular arithmetic is a
good intro to elementary group and number theory, and
an entre into cryptography.  I pursue these topics, with
Python, here: http://www.inetarena.com/~pdx4d/ocn/crypto0.html

Kirby