Answer the question
In order to leave comments, you need to log in
How to work with multiple instances of a class at the same time?
Hello!
I'm doing an assignment from Mike Dawson's Python 3 tutorial. I
need to write a program that simulates a farm.
What is the point: several little animals are created, each has a mood attribute (calculated from the sum of the "hunger" and "boredom" parameters). It should be possible to feed / play / find out the mood of all the animals at the same time, but I just can’t figure out how to do this.
In the previous version of the program, where there was only one animal, everything is simple - there is only one animal, therefore, there is only one instance of the class, the name of which I am just a hardcoder.
Immediately, immediately to all instances (of which you can create at least a million), certain methods must be applied.
Below is the source code, see the main() method. Where it says "ANIMALS", the name of a single copy was previously hardcoded. class NewCritter, to which the methods were applied.
How can this problem be solved?
Z.Y. I also want to implement the ability to select an action (eg feed), enter the name of the animal, and after that the name of this class instance is found by name and the selected method is applied to it. Is it possible?
Thanks in advance to all who respond!
class NewCritter(object):
def __init__(self, name):
print('Появилась новая зверушка!')
import random
hunger = random.randint(0, 10)
boredom = random.randint(0, 10)
self.name = name
self.hunger = hunger
self.boredom = boredom
# накормить
def eat(self):
print('Сколько еды вы дадите зверюшке (КГ)?')
food = None
while food not in range(1, 6):
food = int(input('Введите число от 1 до 5: '))
self.hunger -= food
print('Вы дали зверюшке ровно {} КГ еды!'.format(food))
if self.hunger < 0:
self.hunger = 0
self.__pass_time()
# поиграть
def play(self):
print('Сколько минут вы готовы поиграть со зверюшкой?')
fun = None
while fun not in range(1, 6):
fun = int(input('Введите число от 1 до 5: '))
self.boredom -= fun
print('Вы поиграли со зверюшкой ровно {} минут!'.format(fun))
if self.boredom < 0:
self.boredom = 0
self.__pass_time()
# рассчёт настроения
@property
def mood(self):
unhappiness = self.hunger + self.boredom
if unhappiness < 5:
m = "прекрасно!"
elif 5 <= unhappiness <= 10:
m = "неплохо."
elif 11 <= unhappiness <= 15:
m = "так себе.."
else:
m = "ужасно!"
return m
# зверюшка представляется и говорит о своём настроении
def talk(self):
print('Привет! Меня зовут {} и я чувствую себя {}'.format(self.name, self.mood))
print('Уровень голода: ', self.hunger)
print('Уровень скуки: ', self.boredom)
self.__pass_time()
# увеличивает hunger и boredom на 1 пункт после каждого действия из меню
def __pass_time(self, turn=1):
self.hunger += turn
self.boredom += turn
def generator():
# генерим зверюшек
num = None
while type(num) != int:
num = input('Сколько зверюшек вы хотите создать? Введите целое число: ')
critters = []
counter = 0
string = 'crit'
while counter != num:
counter += 1
critters.append(string + str(counter))
for crit in critters:
crit_name = input('Как назовёте зверюшку? Введите имя: ')
crit = NewCritter(name=crit_name)
def main():
generator()
choice = None
while choice != '0':
print('''
Мои зверюшки
0 - Выйти
1 - Узнать о самочувствии ваших зверюшек
2 - Покормить зверюшек
3 - Поиграть со зверюшками
''')
choice = input('Ваш выбор: ')
if choice == '0':
print('До свидания!')
elif choice == '1':
ЗВЕРЮШКИ.talk()
elif choice == '2':
ЗВЕРЮШКИ.eat()
elif choice == '3':
ЗВЕРЮШКИ.play()
else:
print('Варианта {} нет в меню. Введите число от 0 до 3.'.format(choice))
continue
main()
Answer the question
In order to leave comments, you need to log in
It seems to me that the answers to your questions are easily found by a search engine, incl. search on the Toaster... For example: one , two , etc.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question