我正在創建一個程式,其中制作了一個動物園,并使用喂養動物的功能來檢查它們是否是夜間活動,然后激活“吃”功能。
當我運行代碼時,它似乎遍歷所有動物,無論它們是否是夜間活動,即使有一個 if 陳述句要檢查,但它應該只回圈那些不是的,并輸出“吃”的結果那些。
我懷疑“吃”功能是原因,但我不知道為什么。
關于如何解決它的任何想法?
class Animal:
def __init__(self, name, weight):
self.name = name
self.weight = weight
class Elephant(Animal):
def __init__(self, name, weight):
super().__init__(name, weight)
self.species = "elephant"
self.size = "enormous"
self.food_type = "herbivore"
self.nocturnal = False
class Tiger(Animal):
def __init__(self, name, weight):
super().__init__(name, weight)
self.species = "tiger"
self.size = "large"
self.food_type = "carnivore"
self.nocturnal = True
class Racoon(Animal):
def __init__(self, name, weight):
super().__init__(name, weight)
self.species = "racoon"
self.size = "small"
self.food_type = "omnivore"
self.nocturnal = True
class Gorilla(Animal):
def __init__(self, name, weight):
super().__init__(name, weight)
self.species = "gorilla"
self.size = "large"
self.food_type = "herbivore"
self.nocturnal = False
zoo = []
def add_animal_to_zoo(animal_type, name, weight):
if animal_type == "elephant":
animal = Elephant(name, weight)
zoo.append(animal)
return zoo
elif animal_type == "racoon":
animal = Racoon(name, weight)
zoo.append(animal)
return zoo
elif animal_type == "gorilla":
animal = Gorilla(name, weight)
zoo.append(animal)
return zoo
elif animal_type == "tiger":
animal = Tiger(name, weight)
zoo.append(animal)
return zoo
add_animal_to_zoo("elephant", "john", 111)
add_animal_to_zoo("elephant", "shaun", 200)
add_animal_to_zoo("racoon", "larry", 2)
add_animal_to_zoo("racoon", "jim", 4)
add_animal_to_zoo("gorilla", "jack", 400)
add_animal_to_zoo("tiger", "sarah", 500)
add_animal_to_zoo("tiger", "lucy", 300)
add_animal_to_zoo("tiger", "liam", 250)
def sleep(self):
if self.nocturnal:
print("This animal sleeps at night")
else:
print("This animal sleeps during the day")
def eat(food):
for animal in zoo:
if food == "plants":
if animal.food_type == "herbivore" or animal.food_type == "omnivore":
print(f'{animal.name} the {animal.species} thinks {food} is yummy!')
else:
print(f'{animal.name} the {animal.species} does not eat {food}')
elif food == "meat":
if animal.food_type == "carnivore" or animal.food_type == "omnivore":
print(f'{animal.name} the {animal.species} thinks {food} is yummy!')
else:
print(f'{animal.name} the {animal.species} does not eat {food}')
def feed_animals(time='day'):
for animal in zoo:
if time == 'day':
if not animal.nocturnal:
eat("plants")
else:
eat("meat")
else:
return None
if time == 'night':
if animal.nocturnal:
eat("plants")
else:
eat("meat")
else:
return None
feed_animals()
uj5u.com熱心網友回復:
我懷疑“吃”功能是原因,但我不知道為什么。
該eat(food)函式作為引數獲取并food回圈遍歷所有動物,而不是作為引數 ( ),因此它可以在不遍歷所有動物的情況下作業(跳過此函式),因為這已經在函式中完成。foodanimaleat(animal, food)for animal in zoo:feed_animals
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/517378.html
標籤:Python功能循环班级if 语句
