[Tutor] dynamic class method creation?

maddox flower maddoxflower at web.de
Mon Nov 10 16:21:20 EST 2003


Hi there,

here's my problem:
I'd like to be able to create a class method dynamically.
Some background information: I am using the Numeric module which 
provides a nice and fast function called sum() to sum over the elements 
of an array, but only along one axis of the array. Now, I want to sum 
over ALL elements of the array, so I need to apply sum() repeatedly. No 
problem here as long as I know the rank (i.e. the number of axes or 
dimensions) of the array beforehand. Which I do not. Of course I could 
just do the sum recursively, but unfortunately this is quite slow since 
it involves checking conditions at runtime. I need to run this sum 
business like maybe a couple of million times in my program, so slowness 
really is an issue.

Consider the following class. Depending on the rank of the array which 
is used to create a class instance, the sumArray() method should look 
different:

class ArrayContainer:
   def __init(self, array):
     self.array = array
     # create sumArray() method dynamically at this place!

   def sumArray(self):
     ## if rank of array = 1, i.e. only one axis (e.g. [1, 2, 3]):
     return sum(self.array)
     ## if rank of array = 2 (e.g. [[1, 2, 3], [4, 5, 6]]):
     return sum(sum(self.array))
     ## if rank of array = n:
     return sum(sum(...sum(self.array)...))   # call sum() n times

Actually checking the rank of the array INSIDE the sumArray() method 
again decreases speed significantly when running through the check some 
million times!

So, how can this dynamic method creation be achieved? Can I use the exec 
statement for this?

Cheers,     Maddox





More information about the Tutor mailing list