Numeric array of objects

B

beliavsky

You create a 1-D Numeric array of n floats with

x = zeros(n,Float)

How do you create a Numeric array of n instances of class 'xy', where
for example xy is defined as follows:

class xy:
def __init__(self,x=0.0,y=0.0):
self.x = x
self.y = y

I want the elements of the array to be initialized to the default
value of xy, (0.0,0.0). I have read the Martelli's explanation on p309
of the book "Python in a Nutshell", but I still don't get it.
 
L

Larry Bates

What you want is n "instances" of the class xy.
Since __init__ method is called when an instance
is created, the instance.x and instance.y
attributes will be 0.0, 0.0 unless you set them
to something different (as arguments to the
instance creation).

class xy:
def __init__(self,x=0.0,y=0.0):
self.x = x
self.y = y

n=10
x=[xy() for j in range(10)]

after that

x[0].x equals 0.0
x[0].y equals 0.0
..
..
..
x[9].x equals 0.0
x[9].y equals 0.0

I "think" this is what you want, but I'm not certain.

-Larry
 
J

Josiah Carlson

You create a 1-D Numeric array of n floats with
x = zeros(n,Float)

How do you create a Numeric array of n instances of class 'xy', where
for example xy is defined as follows:

class xy:
def __init__(self,x=0.0,y=0.0):
self.x = x
self.y = y

I want the elements of the array to be initialized to the default
value of xy, (0.0,0.0). I have read the Martelli's explanation on p309
of the book "Python in a Nutshell", but I still don't get it.


Numeric.array([xy() for i in xrange(n)], Numeric.PyObject)


- Josiah
 
J

John Hunter

> How do you create a Numeric array of n instances of class 'xy', where
> for example xy is defined as follows:

from Numeric import PyObject, array

class xy:
def __init__(self,x=0.0,y=0.0):
self.x = x
self.y = y

a = array([xy() for i in range(10)], typecode=PyObject)

JDH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top