繁体   English   中英

Python,将变量的名称添加到列表/字典

[英]Python, add variable's names to a list/dict

我是POO的初学者。

我实际上是用pygame编码游戏,我想将变量的名称添加到列表或字典中。

我有一个类英雄与INIT

class Hero:
    def __init__(self, posx, posy, image) :
        self.name = "Hero"

        self.posx = posx
        self.posy = posy

        self.image = pygame.image.load(image).convert_alpha()

        self.width = self.image.get_rect()[2]
        self.height = self.image.get_rect()[3]

而且我有一个功能可以在屏幕上显示精灵:

def show(self) :
    display.blit(self.image, (self.posx, self.posy))

它有效,没有问题,我实际上正在使用它:

captainamerica = Hero(100,400, "sprites/captainamerica/base.png")
captainamerica.show()
ironman = Hero(100,400, "sprites/ironman/base.png")
ironman.show()

但我想用这个:

listhero = []
listhero.append(captainamerica)
listhero.append(ironman)
i = 0
while i < len(listhero):
    listhero[i].show()

它不起作用,因为它采用了变量的值而不是变量的名称。

谢谢您的帮助,对不起,如果我的英语不好。

您没有增加i,因此会导致无限循环。

您可以添加

i += 1

在循环结束时。

更好的是,执行以下操作:

for h in listhero:
    h.show()

关于数据结构的选择(如注释中突出显示的那样),使用字典比使用列表更好。 您可以执行以下操作:

heroes = {}
heroes['Captain America'] = Hero(100, 400, 'sprites/captainamerica/base.png')

您实际上可以使用字典:

dictheroes = {}

dictheroes['ironman'] = Hero(100,400, "sprites/ironman/base.png")

保留清单,您也可以

[h.show() for h in listhero]

您可以使用字典,但是blit的顺序将不会是字典中插入的顺序。 如果需要保留blit的顺序,请继续使用列表或使用:

collections.OrderedDict

暂无
暂无

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

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