0

Нужно вызвать функцию voina() правильно и без ошибок, но как? Код:

que4 = input("Имя Марсианина 1 :")
que5 = input("Имя Марсианина 2 :")
a = False

class Marsian:
    population = 0
    def __init__(self,name):
        self.name = name
        print("Создан Марсианин {0}".format(self.name))
        Marsian.population =+1
    if a == True:
        def __del__(self):
            print("{0} уничтожаеться!!!".format(self.name))
            Marsian.population =-1
            if Marsian.population == 0:
                print("{0} был последним...".format(self.name))
            else:
                print("{0} Осталось Марсианов".format(Marsian.population))
    def talk(self):
        print("Привет! Меня зовут Марсианин {}".format(self.name))
    @staticmethod
    def Howmuch():
        print("{0:d} всего нас!".format(Marsian.population))
que = int(input("Сила робота:"))
que2 = input("Имя робота:")
class Robot(Marsian):
    popul = 0

    def __init__(self,name2,strong):
        self.name2 = name2
        self.strong = que
        print("Создан Робот {0}.Его сила {1}".format(self.name2,self.strong))
        Robot.popul += 1
    if a == True:
        def __del__(self):
            print("{0} уничтожаеться!".format(self.name2))
            Robot.popul -= 2
            if Robot.popul == 0:
                print("{0} был последним...".format(self.name2))
            else:
                print("{0} осталось Роботов".format(Robot.popul))
    def talk(self):
        print("Привет ! Меня зовут {0}.Моя сила {1}".format(self.name2,self.strong))
    @staticmethod
    def Muches():
        print("Всего нас {0:d}".format(Robot.popul))
    global voina
def voina(self):
    print("{0} Роботов  с силой {1} VS {2} Марсианининов з силой 0".format(self.name2,self.strong,self.name))
    if (self.strong + Robot.popul) < Marsian.population:
        print("{0} выйграли!!!".format(self.name))
    else:
        print("{0} выйграли!!!".format(self.name2))
obg1 = Marsian(que4)
obg2 = Marsian(que5)
obg3 = Robot(que2,que)
obg1.talk()
obg2.talk()
obg3.talk()
obg1.Howmuch()
obg3.Muches()
obg2.Howmuch()
voina(self)

P.S. Через voina() не получиться, требует что бы внутри него было self, но если его вписать пайтон выводит ошибку:

Traceback (most recent call last):
  File "C:/Users/x/PycharmProjects/untitled12/myinit.py", line 26, in <module>
    class Robot(Marsian):
  File "C:/Users/x/PycharmProjects/untitled12/myinit.py", line 54, in Robot
    voina(self)
NameError: name 'self' is not defined
9
  • метод применяется к экземпляру класса а не к классу.
    – eri
    24 сен 2017 в 10:05
  • тут ещё жуткая смесь методов и глобальных функций. Класс - это типы объектов, не нужно писать в классы то что делается не с самим экземляром, а с чемто другим, особенно с группой других экземпляров
    – eri
    24 сен 2017 в 10:10
  • Спасибо за совет,но ведь это не решает ошибку
    – user266433
    24 сен 2017 в 10:41
  • Вам надо создать виртуальний класс PopulationItem и от него отнаследовать Marsian и Robot. Если хотите получить пример как это сделать выложите здесь полный код 24 сен 2017 в 10:53
  • Спасибо,думаю сам решу,если не получиться выложу
    – user266433
    24 сен 2017 в 10:55

1 ответ 1

2

К сожалению код пришлось усложнить(Виртуальный класс заменен на метакласс). Дело в том что для точного расчета победы нужно хранить объекты в памяти. Просто количества популяции недостаточно.

import weakref


#метакласс для получения списка обьктов класса
class MetaPopulation(type):
    def __init__(self, *args, **kwargs):
        self.__population = {}
        super(MetaPopulation, self).__init__(*args, **kwargs)

    @property
    def population(self):
        return list(self.__population.values())

    def delete(self, pitem):
        del self.__population[id(pitem)]

    def __call__(self, *args, **kwargs):
        pitem = super(MetaPopulation, self).__call__(*args, **kwargs)
        self.__population[id(pitem)] = weakref.proxy(pitem)
        return pitem


class Marsian(metaclass=MetaPopulation):
    def __init__(self, name):
        self.name = name
        print("Создан Марсианин {0}".format(self.name))

    def talk(self):
        print("Привет! Меня зовут Марсианин {}".format(self.name))

    def __del__(self):
        print("{0} уничтожаеться!!!".format(self.name))
        self.__class__.delete(self)
        if self.__class__.population:
            print("{0} Осталось Марсианов".format(len(self.__class__.population)))
        else:
            print("{0} был последним марсианином...".format(self.name))

    @classmethod
    def how_much(cls):
        print("{0:d} всего марсианинов!".format(len(cls.population)))

    @classmethod
    def user_create(cls):
        return cls(input('Имя Марсианина:'))


class Robot(metaclass=MetaPopulation):
    def __init__(self, name, strong):
        self.name = name
        self.strong = strong
        print("Создан Робот {0}. Его сила {1}".format(self.name, self.strong))

    def talk(self):
        print("Привет ! Меня зовут Робот {0}. Моя сила {1}".format(self.name, self.strong))

    def __del__(self):
        print("{0} уничтожаеться!!!".format(self.name))
        self.__class__.delete(self)
        if self.__class__.population:
            print("{0} Осталось Роботов".format(len(self.__class__.population)))
        else:
            print("{0} был последним роботом...".format(self.name))

    @classmethod
    def get_all_strongs(cls):
        return sum(map(lambda robot: robot.strong, cls.population))

    @classmethod
    def how_much(cls):
        print("{0:d} всего роботов!".format(len(cls.population)))

    @classmethod
    def user_create(cls):
        return cls(input('Имя Робота:'), float(input('Сила Робота:')))


def whose_vicroty():
    print("{0} Роботов  с силой {1} VS {2} Марсианининов з силой 0".\
          format(len(Robot.population), Robot.get_all_strongs(), len(Marsian.population)))

    if (len(Robot.population) + Robot.get_all_strongs()) == len(Marsian.population):
        print('Ничья')
    elif (len(Robot.population) + Robot.get_all_strongs()) < len(Marsian.population):
        print('Марсиане победили')
    else:
        print('Роботы победили')


m1 = Marsian.user_create()
m2 = Marsian.user_create()

r1 = Robot.user_create()
r2 = Robot.user_create()

for pitem in (m1, m2, r1, r2):
    pitem.talk()
    pitem.how_much()

whose_vicroty()

Запустить онлайн: https://repl.it/L7Jo/5

13
  • Спасибо за ответ,но могли так сильно не стараться,что-бы понять такой код для меня,не одну неделю потратишь)))
    – user266433
    24 сен 2017 в 12:01
  • Если я не ошибаюсь,что бы сделать metaclass надо импортировать так from abc import *
    – user266433
    24 сен 2017 в 12:03
  • @Taras нет, это абстрактный класс 24 сен 2017 в 12:03
  • не, не надо. Его можно и так делать 24 сен 2017 в 12:03
  • @Taras спрашивайте если что не ясно. Тут вообще самая сложная вещь это метакласс со ссылкой. Но она тоже простая очень 24 сен 2017 в 12:05

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.