为什么我不能使用input()来获取对象?

问题描述 投票:0回答:1

我创建了一个动物列表。然后我问用户,你是什么?当他回答时,我无法让程序在列表中识别它。

class Animal:
    def make_sound(self):
        pass  # This is an abstract method

class Dog(Animal):
    def make_sound(self):
        print("Woof!")

dog = Dog()

animals = [dog, cat, duck]

what = input("What are you? ")

if what in animals : what.make_sound()  
else : print("it's not in the list")

what = dog
if what in animals : what.make_sound()  
else : print("it's not in the list")

这是输出:

What are you? dog
it's not in the list
try it this way, what = dog
Woof!
python list object user-input
1个回答
0
投票

你必须记住,

input()
总是返回一个
str
,所以这意味着你可以只用一个
dict
从它映射到你的一个对象:

class Dog():
    def make_sound(self):
        print("Woof!")

class Cat():
    def make_sound(self):
        print("Meow")

class Duck():
    def make_sound(self):
        print("Quack!")

dog = Dog()
cat = Cat()
duck = Duck()

animals = {'dog':dog, 'cat':cat, 'duck':duck}

what = input("What are you? ")

if what in animals: 
    animals[what].make_sound()  
else:
    print("it's not in the list")

what = 'dog'
if what in animals: 
    animals[what].make_sound()  
else:
    print("it's not in the list")

示例会话:

What are you? duck
Quack!
Woof!
© www.soinside.com 2019 - 2024. All rights reserved.