Python中跨文件的值可访问性

时间:2014-12-23 14:21:17

标签: python

我的文件结构如下

Folder1:
Folder2
Class-with-global-variables-and-static-methods-to-modify-them.py

Folder2:
Myfile-1.py
Myfile-2.py
Master.py

Master.py导入其文件夹中的其他2个文件。 " Class-with-global-variables-and-static-methods-to-modify-them.py"永远不会实例化,并且通过静态方法修改其中的全局值。但我希望这些修改能够在全球范围内持续存在。

例如:

 class Class-with-global-variables-and-static-methods-to-modify-them:

 ...
 ...
 importance = 0
 ...
 ...
 @staticmethod
 def modifyImportance(value):
      Class-with-global-variables-and-static-methods-to-modify-them.imortance = 1

如果Myfile-1.py修改了重要性值,我希望Myfile-2.py可以使用新的重要值,如果它试图访问它的话。

2 个答案:

答案 0 :(得分:0)

你已经做了什么,但是你做错了。

Python没有必要让一个从未实例化过的类只包含静态变量。 Python不是Java,也不需要类。相反,只需在模块级别定义变量并直接修改它们。

答案 1 :(得分:-2)

我认为你只需要在你的var之前追加全局并且事情应该起作用

class Class-with-global-variables-and-static-methods-to-modify-them:
...
 global importance
 importance = 0
 ...
 ...
 @staticmethod
 def modifyImportance(value):
      Class-with-global-variables-and-static-methods-to-modify-them.imortance = 1