如何使用变量调用类?

2024-05-23 16:34:56 发布

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

代码:

class Mega:
    def __init__(self, name, types, moves):
        self.name = name
        self.types = types
        self.moves = moves
  
ropher=Mega('Ropher', 'Sound', ['Screech', 'Coil'])
mijek=Mega('Mijek', 'Light', ['Solar Beam', 'Healing Sunlight'])

input=input('What mega? ').lower
print(f"your mega is {input.name}, a {input.types} type")

我想使用用户输入来决定调用哪个Mega,但我找不到方法。如果输入为“Ropher”,则让它打印Ropher的名称和类型,如果输入为“Mijek”,则打印Mijek的名称。有人能帮忙吗


Tags: 代码nameself名称inputinitdefclass
3条回答

你想要的是一本字典:

megas = {
    'ropher': Mega('Ropher', 'Sound', ['Screech', 'Coil']),
    'mijek': Mega('Mijek', 'Light', ['Solar Beam', 'Healing Sunlight']),
}

input=megas[input('What mega? ').lower()]
print(f"your mega is {input.name}, a {input.types} type")

最好使用字典而不是单独的变量。然后使用字典查找来查找所需的字典

class Mega:
    def __init__(self, name, types, moves):
        self.name = name
        self.types = types
        self.moves = moves

megas = {'ropher': Mega('Ropher', 'Sound', ['Screech', 'Coil']),
         'mijik': Mega('Mijek', 'Light', ['Solar Beam', 'Healing Sunlight'])}

key = input('What mega? ').lower()
print(f"your mega is {megas[key].name}, a {megas[key].types} type")

您也不应该调用变量input,因为您重写了内置函数。在上面,我将其重命名为key

请注意,如果您试图查找的键在字典中不存在,那么您的程序将以KeyError停止。如果要防止出现这种情况,可以首先使用in检查输入是否作为字典中的键之一存在:

if key in megas:
    print(f"your mega is {megas[key].name}, a {megas[key].types} type")
else:
    print("not a valid mega")

或者您可以捕获KeyError

try:
    print(f"your mega is {megas[key].name}, a {megas[key].types} type")
except KeyError:
    print("not a valid mega")

您有多个要通过公共特征查找的对象。在本例中,小写的名称。您可以使用dict按名称索引对象,然后方便地在以后查找它们

class Mega:
    def __init__(self, name, types, moves):
        self.name = name
        self.types = types
        self.moves = moves
  
mega_index = {}
ropher=Mega('Ropher', 'Sound', ['Screech', 'Coil'])
mega_index[ropher.name.lower()] = ropher
mijek=Mega('Mijek', 'Light', ['Solar Beam', 'Healing Sunlight'])
mega_index[mijek.name.lower()] = mijek

my_input=input('What mega? ').lower()
try:
    my_mega = mega_index[my_input]
    print(f"your mega is {my_mega.name}, a {my_mega.types} type")
except KeyError:
    print("No such mega")

这只是冰山一角。你根本不需要那些ropher和mijek变量。它们在字典中,现在可以动态执行

相关问题 更多 >