python - 从类函数更改布尔值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()
解决方案
因为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
...
虽然正如另一个答案所提到的,它似乎可以作为一个全局工作,即使它有点奇怪的用例......一般来说你应该使用上面的两种形式之一
推荐阅读
- python - 使用Tkinter时如何解决Base64图像错误
- c++ - 如何从文件中读取 8 位 RAW 数据
- ios - Firebase 云消息传递:分析仪表板始终显示接收和打开计数为 0
- javascript - 单击显示输入字段何时处于焦点的 div 内的链接
- python - PySpark:根据其他三列的最大值查找一列的值
- c - 操作指向指针数组的指针
- ios - whatsApp/Facebook messenger 是如何制作他们的聊天室视图控制器的?
- php - 文档未使用 php 插入
- sequelize.js - Sequelize - 如何查询一对多关系?
- excel - 如何循环从 href 下载 excel(当所有文件的 href 相同时)