[Tutor] dynamic class method creation?

Lloyd Kvam pythontutor at venix.com
Tue Nov 11 19:41:42 EST 2003

Charming Python: Numerical Python

This article uses a flat attribute to sum the whole array directly.
I think your code would look like:

Hope this helps.  (I haven't used numeric or numarray myself.)

maddox flower wrote:

> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582

More information about the Tutor mailing list