Question

I'm having trouble finding out how to dynamically instantiate multiple instances of a class. For example, I'm given a file with an x,y,z and t coordinate on each line. I want to place each line into a class named Droplet that is uniquely identified bu the x,y because the z position and time varies with time. Each Droplet will have a hashtable that maps a time to a z coordinate.

The big picture is that each line of input specifies a location of a water surface at a point in time and I will be animating this in Blender using python.

The part I'm having trouble with that I don't know how many instances of Droplet I will have to instantiate, so I can't do something like

drop1 = Droplet(0,0)
drop2 = Droplet(0,1)
... and so on

Is there a way for me to automate class instantiation using the unique x,y as an identifier in Python?

Was it helpful?

Solution

Yea just do it in a loop and put the objects into a list:

drops = []
for line in file:
    x, y, z, t = parseFromFile(line)
    drops.append(Droplet(x,y,z,t))

or, more Pythonesque:

drops = [Droplet(*parseFromFile(line)) for line in file]

*here takes the (presumbably four) values returned by parseFromFile and uses them as four arguments for the Droplet instantiation

OTHER TIPS

If you need to uniquely identify them by the x and y direction (and, I guess, overwrite them when a new one with the same coordinates comes along), I'd use a 2-dimensional array indexed by x and y, and store the Droplet objects in that collection. So something like this:

droplets[x][y] = Droplet(x,y,z,t)

You'll have to read up on how to initialize 2-d arrays; you need to first make sure that droplets has enough room in both the x and y directions for all the droplets to fit in. But this way you can pick out any particular droplet you want by its x and y coordinate.

At a high level

drops = []
with open('drop_file.txt', 'r') as f:
    for line in f:
        x, y = line.strip().split()
        drops.append(Droplet(x, y))

then you can loop over the list of droplets when you need to do something to each of them.

this assumes that your file is in the format

x y

x1 y1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top