簡體   English   中英

實例化一個 static 變量,從 python 中的另一個模塊調用

[英]Instantiate a static variable to be called from another module in python

我有一個特殊的問題。

我目前有一個腳本script1生成多個實驗,每個實驗都使用script2運行。 為了運行script1以及所有script2 ,我需要執行 API 調用(對 WandB),並獲取一些數據。 因此,我決定創建一個單獨的 class 來存儲來自這個 API 調用的數據,這樣我就可以成功運行script1 ,然后我也可以成功地獲取數據,而無需在所有script2中重新調用 API 獲取。 此外, script2有自己的參數,我通常通過命令行傳入該參數。 我怎樣才能合並這個新功能,同時仍然能夠從終端調用script2

然而,我的問題是 python 不允許我保留實例化的 static 變量,而是說沒有這樣的屬性。 我想知道是否有解決此問題的方法,而不必在每次運行每個單獨script2時都進行過多的 API 調用。

該問題的一個非常簡單的結構如下:

script1.py

from helper import Helper

import os

print("Running script1")
# This is mimicking our API call
number_from_api = 5
# Record the fetched value as a static variable in a class
hlpr = Helper(number_from_api)
num = Helper.number
print(f"The num fetched is {num}")
for _ in range(num):
    os.system("python3 script2.py")

script2.py

from helper import Helper

print("Running script2!")
result = Helper.number + 2
print(f"New result is {result}")

helper.py

class Helper():

    def __init__(self, number):
        print("Initializing Helper Class")
        Helper.number = number

運行python3 script1.py返回錯誤:

File "C:\my_path\script2.py", line
4, in <module>
    result = Helper.number + 2
AttributeError: type object 'Helper' has no attribute 'number'

如果有人能解決這個確切的問題,或者知道可以避免的解決方法,我們將不勝感激!

為避免您遇到的錯誤,您需要像這樣更改 Helper class。 因為你沒有在script2中實例化Helper class。

class Helper:
    number = 0 # it is required!

    def __init__(self, number):
        print("Initializing Helper Class")
        Helper.number = number

另外,我建議您使用 Redis 或類似的東西來存儲/讀取多個進程之間的共享數據。

暫無
暫無

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

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