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

时间:2019-08-14 20:06:30

标签: python oop object instance

在我的程序中,我在下面定义一个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)

我该如何实现?

1 个答案:

答案 0 :(得分:2)

您将要使用字典。

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

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

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