array of class attributes

beliavsky at aol.com beliavsky at aol.com
Mon Apr 5 12:10:37 EDT 2004


Suppose I define a trivial class composed of x and y coordinates and
create a Numeric array of instances of that class.

class xy:
    def __init__(self,x=0.0,y=0.0):
        self.x = x
        self.y = y
    def __repr__(self):
        return ("%6.2f" % self.x) + (",%6.2f" % self.y)

from xy import xy
from Numeric import zeros,array,PyObject
n = 3
aa = array([xy() for i in xrange(n)], PyObject)
aa[1] = xy(5.0,25.0)
print aa
# not legal -- print aa.x

The output of this program is 
[  0.00,  0.00    5.00, 25.00    0.00,  0.00 ] . 

I would like to be able to get an array [0.00 5.00 0.00] corresponding
to the x component of array aa using the syntax aa.x, but this is not
correct Python.  Array slices of components would also be nice. I
could write a function to return such an array, but I doubt that this
would be efficient in CPU time or memory. I wonder if this capability
could be added to Numarray, the successor of Numeric. Otherwise, it
may be better to write numerical codes using parallel arrays (one for
x, one for y) instead of classes, and the benefits of classes are
lost.

Below is a program showing how this is done in Fortran 95.

module xy_mod
implicit none
type, public :: xy
   real :: x = 0.0, y = 0.0
end type xy
end module xy_mod

program xxy
use xy_mod, only: xy
implicit none
integer, parameter :: n = 3
type(xy)           :: aa(n)
character (len=*), parameter :: fmt_r="(100(2f6.2,4x))"
aa(2) = xy(5.0,25.0)
print fmt_r,aa
print fmt_r,aa%x
print fmt_r,aa(1:2)%x
end program xxy

The output is 

  0.00  0.00      5.00 25.00      0.00  0.00
  0.00  5.00      0.00
  0.00  5.00



More information about the Python-list mailing list