gpt4 book ai didi

python - 在 Python 类中定义全局变量

转载 作者:行者123 更新时间:2023-11-28 19:39:40 25 4
gpt4 key购买 nike

在 Python 类中我有以下方法

def foo(self,arg1, arg2):
global run
run = False

在同一个类中,在我的构造函数中

   while run:
sleep(0.01)
self.each_frame()
self.server.close()
run = True

以这种方式在类方法中调整全局变量是否可以?

最佳答案

这是一个可怕的想法。如果您需要在实例之间共享的变量,请在类中定义它。如果您需要在方法之间共享变量,请在对象上定义它们:

class Foo(object):
this_is_a_class_variable = 0

def __init__(self,*args):
self.this_is_an_object_variable = None

关于python - 在 Python 类中定义全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19793511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com