首页 > 解决方案 > 从类函数更改布尔值python

问题描述

所以我是 python 新手,我目前正在构建语音助手,当 done_main = false 时会终止,但问题是即使我已经触发了退出函数,我也无法将 done_main 的值更改为 false

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()

标签: pythonclassboolean

解决方案


因为done_main附加到类它是类或实例变量而不是全局

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

或者,您可以将其用作类变量

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
       ...

虽然正如另一个答案所提到的,它似乎可以作为一个全局工作,即使它有点奇怪的用例......一般来说你应该使用上面的两种形式之一


推荐阅读