簡體   English   中英

得到 AttributeError: 'module' 對象在從另一個文件導入全局變量時沒有屬性

[英]got AttributeError: 'module' object has no attribute while importing global variable from another file

我有兩個這樣的python文件:

# first.py
global x
if __name__ == "__main__":
    x = 'test_var'

和:

# second.py
import first
class XX(object):
    @staticmethod
    def print_x():
        print first.x

我運行這個腳本:

import second
second.XX.print_x()

我得到這個錯誤:

AttributeError: 'module' object has no attribute 'x'

知道出了什么問題嗎?

first.py的代碼永遠不會運行,因為它不是您的入口點,並且不會直接調用該代碼,這意味着從未定義 x。 使用 first.py 作為您的入口點或將 x 的聲明放入您嘗試訪問它之前調用的方法中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM