擅长:python、mysql、java
<p>您有多个要通过公共特征查找的对象。在本例中,小写的名称。您可以使用<code>dict</code>按名称索引对象,然后方便地在以后查找它们</p>
<pre><code>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")
</code></pre>
<p>这只是冰山一角。你根本不需要那些ropher和mijek变量。它们在字典中,现在可以动态执行</p>