我有2個檔案。檔案 1 有一個函式,其中有一個串列。我正在嘗試在 File2 中列印該串列的內容,但是,出現名稱錯誤?
下面是保存函式的檔案 1,我試圖在檔案 2 中訪問的串列稱為產品。
def news_articles():
search_metric = {
"q": "covid",
"apiKey": "d5da78e207f94fdc8eecd3530acf4edb"
}
base_url = "https://newsapi.org/v2/everything?"
# fetching data in json format
res = requests.get(base_url, params=search_metric)
open_news = res.json()
# getting all articles in a string article
article = open_news["articles"]
# empty list which will
# contain all trending news
global product
product = []
for s in article:
product.append(s["title"])
在file2中,我只是想匯入模塊并列印(產品)
uj5u.com熱心網友回復:
無需將product串列設為全域。盡量避免讓你的函式依賴于全域變數。大多數程式員發現這是一個不好的做法。
您所要做的就是product從news_articles()函式中回傳串列。然后,您file2可以簡單地列印該函式的結果,即product串列。
import file1
print(file1.news_articles())
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377052.html
下一篇:使用json.load函式時出錯
