简体   繁体   English

Python中的动态对象实例化

[英]Dynamic object instantiation in Python

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. 例如,我给出了一个在每一行上都有x,y,z和t坐标的文件。 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. 我想将每一行放入一个名为Droplet的类中,该类由x,y唯一标识,因为z位置和时间随时间变化。 Each Droplet will have a hashtable that maps a time to az coordinate. 每个Droplet都有一个哈希表,可以将时间映射到az坐标。

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. 大图是每一行输入都指定了某个时间点水面的位置,我将使用python在Blender中设置动画。

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 我遇到问题的部分我不知道有多少Droplet实例需要实例化,所以我做不了类似的事情

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? 有没有办法让我使用唯一的x,y作为Python中的标识符来自动化类实例化?

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: 或者,更多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 *这里采用parseFromFile返回的(可预测的四个)值,并将它们用作Droplet实例化的四个参数

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. 如果你需要通过x和y方向唯一地识别它们(并且,我想,当一个具有相同坐标的新方法出现时覆盖它们),我将使用由x和y索引的二维数组,并存储该集合中的Droplet对象。 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. 你需要首先确保液滴在x和y方向都有足够的空间让所有液滴都适合。但是这样你可以通过x和y坐标选出你想要的任何特定液滴。

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 这假定您的文件采用的格式

xy XY

x1 y1 x1 y1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM