更新静态 Python 类变量在通过另一个文件访问时不会更新该变量



我有以下代码:

test.py

class Foo(object):
index = 0
@classmethod
def increase(cls):
while True:
cls.index += 1
print(cls.index)
@classmethod
def get_index(cls):
return cls.index
if __name__ == "__main__":
Foo.increase()

当我运行它时,我可以看到索引的值在增加。

但是,在它运行时,如果在另一个文件中,我会执行以下操作:

test1.py

import test
print(test.Foo.get_index())

然后我得到index=0.为什么索引的值没有更新?

test.py中,你有

if __name__ == "__main__":
...

这样可以防止在导入模块时运行该条件下的任何指令。如果删除该条件(它仍将作为主模块正确运行(,那么您也将在导入时看到值静态递增。

如果你从另一个类调用函数,那么你必须确保它返回一些东西。但是您的函数get_index不会返回任何内容。

试试这个

test.py

class Foo(object):
index = 0
@classmethod
def increase(cls):
while True:
cls.index += 1
print cls.index
@classmethod
def get_index(cls):
return Foo.increase()
if __name__ == "__main__":
Foo.increase()

最新更新