[英]got AttributeError: 'module' object has no attribute while importing global variable from another file
I have two python files like this:我有两个这样的python文件:
# first.py
global x
if __name__ == "__main__":
x = 'test_var'
and:和:
# second.py
import first
class XX(object):
@staticmethod
def print_x():
print first.x
I run this script:我运行这个脚本:
import second
second.XX.print_x()
And I get this error:我得到这个错误:
AttributeError: 'module' object has no attribute 'x'
Any idea what's going wrong?知道出了什么问题吗?
The code in first.py
never runs because it isn't your entry point and the code isn't directly called, meaning x is never defined. first.py
的代码永远不会运行,因为它不是您的入口点,并且不会直接调用该代码,这意味着从未定义 x。 Use first.py as your entry point or put the declaration of x into a method that you call before trying to access it.使用 first.py 作为您的入口点或将 x 的声明放入您尝试访问它之前调用的方法中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.