我创建了一个动物列表。然后我问用户,你是什么?当他回答时,我无法让程序在列表中识别它。
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!
你必须记住,
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!