Home > Net >  Changing boolean value python from class function
Changing boolean value python from class function

Time:10-08

So im new to python and im currently building voice assistant that will get terminate when the done_main = false but the problem is i cant change the value of done_main to false even if i already trigger the exit function

class Persona:
   global done_main
   done_main = True

   def exit():
            global done_main
            done_main = False
            speaker.say("Bye, have a good day!")
            speaker.runAndWait()

CodePudding user response:

since done_main is attached to the class it is a class or instance variable not a global

class Persona:
   done_main = True
   def exit(self): 
       # self.xxxx = instance variable
       self.done_main = False
       # only set it for this "instance"
       ...

alternatively you can use it as a class variable

class Persona:
   done_main = True
   def exit(self): 
       # ClassName.xxxx = class/static variable
       Persona.done_main = False
       # sets it for the class ... not just this instance
       ...

although as mentioned by the other answer it seems to work as a global even if its a bit of a weird use case... in general you should probably use one of the 2 forms above

CodePudding user response:

Working for me:

class Persona:
   global done_main
   done_main = True

   def exit():
            global done_main
            done_main = False
            #speaker.say("Bye, have a good day!")
            #speaker.runAndWait()


print(done_main)    # True
Persona.exit()
print(done_main)    # False

A "cleaner" approach which I might suggest, would be to use variables scoped at the class level, rather than the global level. This should be more maintainable and less confusing for others glancing at the code:

from typing import ClassVar


class Persona:
    done_main: ClassVar[bool] = True

    @classmethod
    def exit(cls):
        cls.done_main = False
        # speaker.say("Bye, have a good day!")
        # speaker.runAndWait()


print(Persona.done_main)  # True
Persona.exit()
print(Persona.done_main)  # False
  • Related