为何无法用input()获取对象?用户输入无法匹配列表中的Animal对象
问题分析与解决
问题根源
你通过input()获取的是字符串(比如输入的"dog"),但animals列表里存储的是Dog类的实例对象。字符串和对象属于完全不同的数据类型,Python无法将两者判定为相等,所以"dog" in animals的结果永远是False,导致程序输出"it's not in the list"。而后续直接将what赋值为dog(实例对象)时,这个对象确实存在于列表中,因此判断成立并执行了发声方法。
另外原代码存在语法错误:cat和duck没有定义对应的类和实例,实际运行会抛出NameError。
解决方案
提供两种实用的解决思路:
思路一:用字典建立名称与实例的映射
将原列表替换为字典,以动物名称字符串作为键,对应实例作为值,直接通过输入的字符串查找目标实例:
class Animal: def make_sound(self): pass class Dog(Animal): def make_sound(self): print("Woof!") class Cat(Animal): def make_sound(self): print("Meow!") class Duck(Animal): def make_sound(self): print("Quack!") # 创建实例 dog = Dog() cat = Cat() duck = Duck() # 建立名称到实例的映射字典 animal_map = { "dog": dog, "cat": cat, "duck": duck } what = input("What are you? ") if what in animal_map: animal_map[what].make_sound() else: print("it's not in the list")
思路二:给动物类添加名称属性
在Animal基类中添加name属性,创建实例时指定名称,后续遍历列表匹配输入的字符串:
class Animal: def __init__(self, name): self.name = name def make_sound(self): pass class Dog(Animal): def make_sound(self): print("Woof!") class Cat(Animal): def make_sound(self): print("Meow!") class Duck(Animal): def make_sound(self): print("Quack!") # 创建带名称的实例 dog = Dog("dog") cat = Cat("cat") duck = Duck("duck") animals = [dog, cat, duck] what = input("What are you? ") # 遍历列表查找名称匹配的实例 for animal in animals: if animal.name == what: animal.make_sound() break else: # 循环未找到匹配项时执行 print("it's not in the list")
内容的提问来源于stack exchange,提问作者Marney Schulz
相关产品推荐
相关产品推荐

