[Edu-sig] python versus __python__

Kirby Urner urnerk at qwest.net
Sat Oct 22 01:22:13 CEST 2005


> This is something I felt comfortable exploring very early on - to the
> extent of having overused it.  I would hate to see you back-end that, as
> I think it is kind of fun to play with.  "let's change the boring old
> rules of math..." kind of thing.
> 

Yes, operator overloading is a big part of my "math through programming"
curriculum.  You want your * and + operators to be "modulo N" for example,
the better to appreciate group theory.  Or we might use * to mean 'compose'
as in:

  >>> def f(x):  return 2*x + 1

  >>> def g(x):  return x**2

  >>> class F(object):

	def __init__(self, func):
	    self.func = func

	def __mul__(self, other):
	    return F(lambda x: self.func(other.func(x)))

	def __call__(self,x):
	    return self.func(x)
	
	
  >>> of = F(f)
  >>> og = F(g)
  >>> of(2)
  5
  >>> f(g(2))
  9
  >>> h = of*og
  >>> h(2)
  9
  >>> j = og*of
  >>> j(2)
  25

I think where a lot of kids will first encounter underunder is not in
__init__ but in __name__, as in that "__name__ == '__main__'" trick for
getting scripts to run at the command line, even as they also serve as class
& function repositories for snake charmers in a Python shell.

Kirby

PS:  since you've been studying subclassing primitive types using __new__,
maybe you could show us a user-defined floating point type that reports two
numbers equal if their absolute value difference is less than e.  Anyone?




More information about the Edu-sig mailing list