Python 从列表中调用类
我有三门课看起来很像这样。只是不同的名字:Python 从列表中调用类,python,pygame,Python,Pygame,我有三门课看起来很像这样。只是不同的名字: class CrossPipe(BasePipe): def __init__(self, position): BasePipe.__init__(self, position) self.current_pos_X = 0 self.current_pos_y = 0 self.flow_rect = Rect(0,0,settings.FLOW_WIDTH, 0)
class CrossPipe(BasePipe):
def __init__(self, position):
BasePipe.__init__(self, position)
self.current_pos_X = 0
self.current_pos_y = 0
self.flow_rect = Rect(0,0,settings.FLOW_WIDTH, 0)
self.flow_rect.left = (settings.TUBE_SIZE / 2) - (settings.FLOW_WIDTH / 2)
def update(self):
BasePipe.update(self)
if self.current_pos_y < settings.TUBE_SIZE:
self.current_pos_y += 1
self.flow_rect.bottom = self.current_pos_y
pygame.draw.rect(self.image, settings.FLOW_COLOR, self.flow_rect, 1)
这将生成一个如下所示的列表:
['BentPipe', 'CrossPipe', 'BentPipe', 'StraightPipe']
列表中的4个块需要显示在屏幕上,但为了在屏幕上绘制它们,我必须能够通过放置add.add(coming_pipes[0](-2,0))
从列表中调用它们,但由于它是一个字符串列表,所以它给出了placed.add(“BentPipe”(-2,0))
,无法调用
那么,如何从列表中调用一个类,或者将这些类添加到列表中而不使用字符串呢
顺便说一句,我没有太多的编码知识。不要把类的名称放在列表中;把课程放在自己的位置上
pipes = (StraightPipe, BentPipe, CrossPipe)
coming_pipes = []
done = 0
while done != 4:
coming_pipes.append(random.choice(pipes))
done += 1
或者更简单地说
coming_pipes = random.choices(pipes, k=4)
只是不必费心于
\uuuuu name\uuuu
,只需添加类本身。(虽然在实践中,在数组中包含实例可能比在类中更容易——如果您事先知道将给构造函数提供哪些参数的话。)只需删除。\uuuu name\uuu
@RobinZigmond,那么列表将如下所示:[,,]@AndreasSB02,这有什么问题?这意味着您的列表包含可以根据需要调用的类。不用担心它们的字符串表示看起来“奇怪”,是吧?如果你只是想做你想做的事:place.add(coming_pipes[0](-2,0))
应该很好。或者只是coming_pipes=random.choices(pipes,k=4)
。我认为对于OP的学习来说,除了选择之外,列表理解是值得的。
coming_pipes = random.choices(pipes, k=4)