当通过另一个fi访问时,更新静态Python类变量不会更新该变量

2024-04-25 00:41:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

你知道吗测试.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()

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

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

测试1.py

import test

print(test.Foo.get_index())

然后我得到index=0。为什么索引的值没有更新?你知道吗


Tags: 代码pytesttruegetindexobjectfoo
2条回答

test.py中,您有

if __name__ == "__main__":
    ...

如果导入了模块,则会阻止在该条件下运行任何指令。如果删除该条件(它仍将作为主模块正确运行),那么在导入时也将看到静态的值增量。你知道吗

如果您是从另一个类调用函数,那么您必须确保它返回一些东西。但是你的函数get\u index没有返回任何东西。你知道吗

试试这个

你知道吗测试.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()

相关问题 更多 >