[英]How do I use a variable to call a class?
代码:
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,但我找不到 go 的方法。 这个想法是让它打印 Ropher 的名字,如果输入是“ropher”,则输入,如果输入是“mijek”,则打印 Mijek 的名字。 有人可以帮忙吗?
最好使用字典而不是单独的变量。 然后,您使用字典查找来查找您想要的那些。
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
,因为你覆盖了内置的 function。 在上面,我已将其重命名为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 变量。 它们在字典中,现在可以动态操作。
你想要的是一本字典:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.