Home > Back-end >  How can I change the value of a variable from another class in Python?
How can I change the value of a variable from another class in Python?

Time:05-12

I tried research, but all I could find was methods to access an another's class variable, so here's my problem:

I want my Monster() class to have in it's method interact a code that would subtract -10 from a variable pkt in Player() class.

I tried:

super(Player, self)._ _init_ _(pkt) -= 10

but it printed SyntaxError saying "it's an illegal expression for augmented assignment."

Could you help? Here's the code:

from abc import ABC, abstractmethod
from random import random

class GameObject(ABC):
    def __init__(self, pkt):
        self.pkt = pkt

    @abstractmethod

    def is_alive(self):
        return self.pkt > 0

    def interact(self):
        pass


class Player(GameObject):
    def __init__(self):
        super().__init__(50)

    def is_alive(self):
        super().is_alive()

    def interact(self):
        pass

class Door(GameObject):
    def __init__(self):
        super().__init__(50)

    def is_alive(self):
        pass

    def interact(self):
        print("Player went through the door.")


class Monster(GameObject):
    def __init__(self):
        super().__init__(50)

    def is_alive(self):
        pass

    def interact(self):
        super(Player, self).__init__(pkt) -= 10

        print('Player killed the Monster.')


p1 = Player()
board = []

for i in range(0,10):
    if random() < 0.70:
        board.append(Monster())
    else:
        board.append(Door())

for i in board:
    if p1.is_alive() == False:
        break
    else:
        i.interact()
        print(p1.pkt)

CodePudding user response:

All you need to do is

def interact(self, player):
    player.pkt -= 10

with player of type Player.

  • Related