从对象名称(字符串)获取对象

2024-03-28 22:02:24 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的程序中,我在下面定义了一个survivor类并对其进行了实例验证

class survivor(object) :
    def __init__(self, fname, sname, age, currhealth, maxhealth, currwill, maxwill,currspeed,maxspeed, ability):
        self.fname = fname
        self.sname = sname
        self.age = age
        self.health = currhealth
        self.maxhealth = maxhealth
        self.will = currwill
        self.maxwill = maxwill
        self.speed = currspeed
        self.maxspeed = maxspeed
        self.ability = ability

Samuel = survivor("Samuel","Jordie",17,6,6,2,2,4,4,"Strength")
Marie = survivor("Marie","Wems",16,4,4,5,5,4,4,"Heal")
Cumbo = survivor("Cumbo","Chan",17,3,3,4,4,3,3,"Consume")
Sinead = survivor("Sinead","Mess",17,5,5,5,5,6,6,"Tools")
Maria = survivor("Maria","Wiks",16,4,4,5,5,2,4,"Eat")

例如,用户选择4个幸存者并创建这些幸存者的名单

chosen_survivors = ["Samuel","Maria","Cumbo","Sinead"]

然后我想将所选幸存者的一些属性呈现给用户,不管他们选择哪个幸存者

例如

print(chosen_survivors[0].health)

我如何做到这一点


Tags: selfagefnamesamuelsurvivormariaabilitysname
1条回答
网友
1楼 · 发布于 2024-03-28 22:02:24

你会想用字典的

survivors = {
  "Samuel": survivor(...),
  "Marie": survivor(...),
  ...
}

chosen = ["Samuel", "Marie", ...]

print(survivors[chosen[0]].health)  # prints Samuel's health

相关问题 更多 >