@Iceforest

Как обратиться к значению другого класса и изменить его?

есть 3 класса: Кошка, Человек, Дом
У кошки есть свой дом. У человека свой. Человек ловит кошку и переселяет ее в свой дом, добавляя в список.
Проблема возникает в функции класса кошка def cat_rips_off_wallpaper(self) , из нее нужно как то обратиться к классу человека и изменять значение self.dirt, но данная функция не имеет такого параметра, а если его присвоить , то параметр живет отдельно от параметра Человека. self.dirt это параметр грязи в доме человека.
from random import randint
from termcolor import cprint
class Cat:

    def __init__(self, name):
        self.name = name
        self.fullness = 50
        self.house = 'cat_house'

    def __str__(self):
        return 'Я - {}, сытость {}'.format(
            self.name, self.fullness,
        )

    def eat(self):
        if self.house.cat_food >= 10:
            cprint('{} поел'.format(self.name), color='yellow')
            self.fullness += 20
            self.house.cat_food -= 10
        else:
            cprint('{} нет еды'.format(self.name), color='red')

    def go_to_the_house(self, house):
        self.house = house
        cprint('{} Вьехал в дом'.format(self.name), color='cyan')

    def sleep(self):

        self.fullness -= 10

    def cat_rips_off_wallpaper(self):
        self.fullness -= 10
        self.house.dirt += 5

    def act(self):
        if self.fullness <= 0:
            cprint('{} умер...'.format(self.name), color='red')
            return
        dice = randint(1, 4)
        if self.fullness < 20:
            self.eat()
        elif dice == (1, 2):
            self.eat()
        elif dice == 3:
            self.cat_rips_off_wallpaper()
        elif dice == 4:
            self.sleep()


class Man:

    def __init__(self, name):
        self.name = name
        self.fullness = 50
        self.house = 'house'
        self.cat = None
        self.list = []
        self.food = 50
        self.cat_food = 0
        self.money = 50
        self.dirt = 0

    def __str__(self):
        return 'Я - {}, сытость {} , В доме еды осталось {}, кошачей еды {}, денег осталось {}, грязи {}'.format(
            self.name, self.fullness, self.food, self.cat_food, self.money, self.dirt
        )

    def eat(self):
        if self.food >= 10:
            cprint('{} поел'.format(self.name), color='yellow')
            self.fullness += 10
            self.food -= 10
        else:
            cprint('{} нет еды'.format(self.name), color='red')

    def work(self):
        cprint('{} сходил на работу'.format(self.name), color='blue')
        self.money += 150
        self.fullness -= 10

    def catch_cat(self, cat):
        self.cat = cat
        self.list.append(cat)
        cat.house = self.house
        cprint('{} словил кота'.format(self.name), color='green')
        self.fullness -= 20

    def cleaning(self):
        cprint('{} убрался'.format(self.name), color='green')
        self.fullness -= 20
        self.dirt -= 100

    def shopping(self):
        if self.money >= 100:
            cprint('{} сходил в магазин за едой'.format(self.name), color='magenta')
            self.money -= 100
            self.food += 50
            self.cat_food += 50
        else:
            cprint('{} деньги кончились!'.format(self.name), color='red')

    def act(self):
        if self.fullness <= 0:
            cprint('{} умер...'.format(self.name), color='red')
            return

        dice = randint(1, 6)
        if self.fullness < 50:
            self.eat()
        elif self.food < 10:
            self.shopping()
        elif self.money < 150:
            self.work()
        elif self.cat_food < 10:
            self.work()
        elif self.dirt == 100:
            self.cleaning()
        elif dice == 1:
            self.work()
        elif dice == 2:
            self.eat()


class House:

    def __init__(self):
        self.food = 50
        self.cat_food = 50
        self.money = 50
        self.dirt = 0

    def __str__(self):
        return 'В доме еды осталось {}, кошачей еды {}, денег осталось {}, грязи {}'.format(
            self.food, self.cat_food, self.money, self.dirt
        )


man = Man(name='Бивис')
cat = Cat(name='Рыжик')
man.catch_cat(cat)
citizens = [
    Man(name='Бивис'),
    Cat(name='Рыжик'),
]

for day in range(1, 366):
    print('================ день {} =================='.format(day))
    for citisen in citizens:
        citisen.act()
    print('--- в конце дня ---')
    for citisen in citizens:
        print(citisen)
    print(man.house)

подскажите как исправить?
  • Вопрос задан
  • 141 просмотр
Решения вопроса 1
@Iceforest Автор вопроса
class Cat:

    def __init__(self, name):
        self.name = name
        self.fullness = 50
        self.house = 'cat_house'

    def __str__(self):
        return 'Я - {}, сытость {}'.format(
            self.name, self.fullness,
        )

    def eat(self):
        if self.house.cat_food >= 10:
            cprint('{} поел'.format(self.name), color='yellow')
            self.fullness += 20
            self.house.cat_food -= 10
        else:
            cprint('{} нет еды'.format(self.name), color='red')

    def go_to_the_house(self, house):
        self.house = house
        cprint('{} Вьехал в дом'.format(self.name), color='cyan')

    def sleep(self):

        self.fullness -= 10

    def cat_rips_off_wallpaper(self,house):
        self.house=house
        self.fullness -= 10
        self.house.dirt += 5

    def act(self):
        if self.fullness <= 0:
            cprint('{} умер...'.format(self.name), color='red')
            return
        dice = randint(1, 4)
        if self.fullness < 20:
            self.eat()
        elif dice == (1, 2):
            self.eat()
        elif dice == 3:
            self.cat_rips_off_wallpaper(house)
        elif dice == 4:
            self.sleep()


class Man:

    def __init__(self, name, house):
        self.name = name
        self.fullness = 50
        self.house = house
        self.cat = None
        self.list = []
        self.food = 50
        self.money = 50

    def __str__(self):
        return 'Я - {}, сытость {}'.format(
            self.name, self.fullness,
        )

    def eat(self):
        if self.food >= 10:
            cprint('{} поел'.format(self.name), color='yellow')
            self.fullness += 10
            self.house.food -= 10
        else:
            cprint('{} нет еды'.format(self.name), color='red')

    def work(self):
        cprint('{} сходил на работу'.format(self.name), color='blue')
        self.house.money += 150
        self.fullness -= 10

    def catch_cat(self, cat):
        self.cat = cat
        self.list.append(cat)
        cat.house = self.house
        cprint('{} словил кота'.format(self.name), color='green')
        self.fullness -= 20

    def cleaning(self):
        cprint('{} убрался'.format(self.name), color='green')
        self.fullness -= 20
        self.house.dirt -= 100

    def shopping(self):
        if self.house.money >= 100:
            cprint('{} сходил в магазин за едой'.format(self.name), color='magenta')
            self.house.money -= 100
            self.house.food += 50
            self.house.cat_food += 50
        else:
            cprint('{} деньги кончились!'.format(self.name), color='red')

    def act(self):
        if self.fullness <= 0:
            cprint('{} умер...'.format(self.name), color='red')
            return

        dice = randint(1, 6)
        if self.fullness < 50:
            self.eat()
        elif self.house.food < 10:
            self.shopping()
        elif self.house.money < 150:
            self.work()
        elif self.house.cat_food < 10:
            self.work()
        elif self.house.dirt == 100:
            self.cleaning()
        elif dice == 1:
            self.work()
        elif dice == 2:
            self.eat()


class House:

    def __init__(self):
        self.food = 50
        self.cat_food = 50
        self.money = 50
        self.dirt = 0

    def __str__(self):
        return 'В доме еды осталось {}, кошачей еды {}, денег осталось {}, грязи {}'.format(
            self.food, self.cat_food, self.money, self.dirt
        )


house = House()
man = Man(name='Бивис', house=house)
cat = Cat(name='Рыжик')
man.catch_cat(cat)

citizens = [
    Man(name='Бивис',house=house),
    Cat(name='Рыжик'),
]


for day in range(1, 366):
    print('================ день {} =================='.format(day))
    for citisen in citizens:
        citisen.act()
    print('--- в конце дня ---')
    for citisen in citizens:
        print(citisen)
    print(man.house)
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы