Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 从定义的类动态创建实例_Python 3.x_Pygame - Fatal编程技术网

Python 3.x 从定义的类动态创建实例

Python 3.x 从定义的类动态创建实例,python-3.x,pygame,Python 3.x,Pygame,我正在尝试做一些模拟/游戏,在其中我想通过点击跟随万有引力的物体来创造行星。我这样做是为了了解类和Pygame 我有一节课 class行星: 行星=[] position=np.数组([100100],dtype=float) velocity=np.数组([0,0],dtype=float) 加速度=np.数组([0,0],dtype=浮点) 质量=10。 定义初始化(自我, 位置=np.数组([100100],数据类型=浮点), 速度=np.数组([0,0],数据类型=浮点), 加速度=np

我正在尝试做一些模拟/游戏,在其中我想通过点击跟随万有引力的物体来创造行星。我这样做是为了了解类和Pygame

我有一节课

class行星:
行星=[]
position=np.数组([100100],dtype=float)
velocity=np.数组([0,0],dtype=float)
加速度=np.数组([0,0],dtype=浮点)
质量=10。
定义初始化(自我,
位置=np.数组([100100],数据类型=浮点),
速度=np.数组([0,0],数据类型=浮点),
加速度=np.数组([0,0],dtype=浮点),
质量=10。):
self.\uuuuuu类\uuuuuuu.planets.append(self)
self.position=位置
自速度=速度
自身质量=质量
我正在尝试使用Pygame中的事件创建行星,使用鼠标位置作为行星位置/速度

为True时:
屏幕光点(暗示,(0,0))
对于pygame.event.get()中的e:
如果e.type==pygame.QUIT:
pygame.quit()
sys.exit()
如果e.type==pygame.MOUSEBUTTONDOWN:#获取行星位置
mx,my=pygame.mouse.get_pos()
如果e.type==pygame.MOUSEBUTTONUP:#获取行星方向并创建行星
mx2,my2=pygame.mouse.get_pos()

我知道如何创建单个行星,或者使用预先创建的行星,但是否可以使用生成的名称动态创建它们?

一个选项是将类对象附加到列表中,并通过如下索引访问它

list_[index]  # index is an integer
另一个选项是将它们附加到允许按名称访问的字典中,如下所示:

planets = dict()
for i in range(your_range):
    planets[f'planet_nr_{i}'] = Planet()
planet = planets['planet_nr_2']
这样,您可以通过变量名访问每个类,如下所示:

planets = dict()
for i in range(your_range):
    planets[f'planet_nr_{i}'] = Planet()
planet = planets['planet_nr_2']
“但是有可能用生成的名称动态创建它们”是什么意思?您不需要为行星生成变量。“名字”。您可以通过订阅访问这些平面:
planet.planets[i]
其中
ì
是列表中行星的索引。