从定义的类动态创建实例

问题描述

我正在尝试进行某种模拟/游戏,我想通过单击引力来创建行星。我这样做是为了了解课程和Pygame。

我上课

class planet:
    
    planets=[]
    
    position     = np.array([100,100],dtype=float)
    veLocity     = np.array([  0,0],dtype=float)
    acceleration = np.array([  0,dtype=float)
    mass         = 10.
    
    def __init__(self,position     = np.array([100,dtype=float),veLocity     = np.array([  0,acceleration = np.array([  0,mass         = 10.):
        
        self.__class__.planets.append(self)
        self.position = position
        self.veLocity = veLocity
        self.mass     = mass

我正在尝试使用Pygame中的事件来创建行星,并使用鼠标位置作为行星位置/速度

while True:
    screen.blit(hintergrund,(0,0))
    
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
            
        if e.type == pygame.MOUSEBUTTONDOWN: #get planet position
            mx,my = pygame.mouse.get_pos()
            
        if e.type == pygame.MOUSEBUTTONUP: #get planet direction and create planet
            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']