[英]How do i get my program to display a noise that the animal makes if the input a dog, cat or bird
name = input("What is your pet's name?")
species = input("What type of pet is it?")
age = input("How old is your pet?")
class Pet:
def __init__(self, name, species, age, noise):
self.name = name
self.species = species
self.age = age
self.noise = noise
def setNoise(self, noise):
self.noise = "WOOF"
elif species == cat:
self.noise = "MEOW!"
elif species == bird:
self.noise = "CAWW!"
else:
self.noise = "Animal Noise"
def get_type(self):
print("Pet")
def toString(self):
return"{} is a {} and is {} years old".format(self.name,self.species,self.age,self.noise)
myPet = Pet(name,species,age,noise)
print(noise, myPet.toString())
i cannot figure out how to make my program display a noise when i type a certain animal in it, such as a dog, cat, or bird. 当我在其中键入某些动物(如狗,猫或鸟)时,我不知道如何使程序显示噪音。 any help would be amazing.
任何帮助都将是惊人的。 I keep running into the error that noise is not defined.
我不断遇到未定义噪声的错误。 also when i try to use my species input to check if it equals dog it errors out.
当我尝试使用我的物种输入来检查它是否等于狗时,也会出错。
I think this might be what you're trying to get. 我认为这可能就是您想要得到的。 You used the
cat
, bird
, etc. variables without defining them. 您使用了
cat
, bird
等变量,但未定义它们。 I assume these should be strings. 我认为这些应该是字符串。 I also got rid of the
setNoise
function which didn't seem to have a purpose. 我也摆脱了似乎没有目的的
setNoise
函数。 Since the noise is based on the species, I set it at __init__
. 由于噪声是基于物种的,因此将其设置为
__init__
。 Python also has a special method called __str__
. Python还具有一种称为
__str__
的特殊方法。 If you set this, then when I call print(myPet)
it will print the return value of myPet.__str__()
. 如果设置了此项,那么当我调用
print(myPet)
,它将打印myPet.__str__()
的返回值。 This is better to use than defining your own string method because it gets called automatically when printing. 这比定义自己的字符串方法要好用,因为在打印时会自动调用它。
name = input("What is your pet's name?")
species = input("What type of pet is it?")
age = input("How old is your pet?")
# you might want to set age = int(age) if age is, e.g., an integer number of years
class Pet:
def __init__(self, name, species, age):
self.name = name
self.species = species
self.age = age
if species == "dog":
self.noise = "WOOF"
elif species == "cat":
self.noise = "MEOW!"
elif species == "bird":
self.noise = "CAWW!"
else:
self.noise = "Animal Noise"
def get_type(self):
print("Pet")
def __str__(self):
return"{} is a {} and is {} years old".format(self.name,self.species,self.age,self.noise)
myPet = Pet(name, species, age)
print(myPet.noise, myPet)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.