Problem with global variable


I am preparing an exam and I have been doing several exercises, the problem arises when I get to the part of object-oriented programming (OOP) in this exercise:


Write a class that allows you to represent the character of a video game.   A character has a name (or nickname), a percentage of life (or health),   a power (its name, for example, "rotating kick"),   and a measure of damage (whole number between 0 and 100).

  • Implement a method to print the information of a character using the print ()

  • command   
  • Implement a method that allows you to attack another character (which is received as a parameter).   The attack of the character (p1) takes life from the character that is attacked (p2),   using the following function:   new_life (p2) = current_life (p2) - measure_of_damage (p1)

  • Implement a method that indicates (returning True) if a character is alive (health> 0)

  • Create 3 characters called pj1, pj2 and pj3 (with the percentage of health and power that you want),   pj1 must attack pj2 and pj3   "" "


    This is the code I have:

    global  vida_queda
    vida_queda = 0
    class Personaje:
        def __init__(self, nickname, vida, poder, daño):
            self.nickname = nickname
            self.vida = vida
            self.poder = poder
            self.daño = daño
        def __repr__(self):
            return("su nombre era " + self.nickname + " " + "se decia que habia vivido " + " " +  self.vida + " "+ "tantos años" + " " + "su ataque especial era" +" "+ self.poder + " " + "y el daño que infligian era " + " " +self.daño)
        def atacar(self,atacante):
            vida_queda = int(self.vida) - int(atacante.daño)  #Tuve que usar el método int() para que funcionara  
            return( vida_queda)
        def checklife(self):
            if vida_queda <= 0:  #Tuve que usar el método int() para que funcionara
                return("i'm dead")
    p1 = Personaje("el_gaucho", str(100), "mono borracho", str(30))
    p2 = Personaje("'gaucho_Bataraz'", str(30), "facón giratorio", str(250))
    p3 = Personaje("'Dura'", "120", "golpe de campo", "300")

    My problem is that it always returns i'm dead , when I have clearly tried to attack a character with a lot of life with one with very little damage, is there any How is the variable saved or is it not?

    asked by noob programer 18.02.2018 в 21:06

    1 answer


    Your problem is caused by the global variable vida_queda . In general, the use of global variables is not recommended.

    The most elegant solution to your problem is to make vida_queda be one more attribute of each of the objects, initializing it in __init__() with self.vida_queda=0 (and do not forget to put in front self. when change in atacar() and check it in checklife() .

    EDITING Rereading the statement, I realize that maybe the variable vida_queda is not necessary, and what the method atacar() should do is simply decrease self.vida (and that same attribute would be the one that is checked from checklife() .

    Additional explanation

    If you also want to know why it did not work for you when it was a global variable, read on, but I warn you that we get into "depths".

    When you initialize a variable outside of any function, it is called a "global variable". These variables can be used later from any of the functions of the same module peero ... if in one of those functions you try to modify the value of that variable, then python will create another variable local instead of changing the value of the global.

    For this reason, when in atacar() you try to change the value of vida_queda , in reality you will be creating a local variable with the same name, within that function. Therefore, when checking the value from the function checklife() you are dead, because the global variable vida_queda has not been modified and remains zero.

    To avoid this strange behavior, you can put within the atacar() function a line that says global vida_queda . This tells Python to modify the global variable instead of creating a new local.

    answered by 18.02.2018 / 22:26