[英]Python - Static Class Variables
我來自C ++背景,經常使用靜態變量來減少必須初始化的時間變量的數量(特別是如果初始化需要很長時間)。 所以從StackOverflow上的其他帖子中,人們建議使用靜態類變量,如下所示:
class MyClass(object):
StaticList1 = [...] # Very large list
StaticList2 = [...] # Very large list
現在,如果在程序執行過程中至少存在一個MyClass實例並且列表只創建一次,那么這很好。 但是,如果在執行的某個階段沒有MyClass的實例,Python似乎會刪除靜態列表(我假設因為引用計數器降為0)。
所以我的問題是,有沒有簡單的方法沒有使用外部模塊初始化StaticList1和StaticList2一次(第一次使用它們)並且永遠不會刪除它們,即使在程序存在之前沒有MyClass實例(或者你刪除了手動列出)?
編輯:
也許我過分簡化了這個問題。 我在做什么:
class MyClass(object):
StaticList = None
def __init__(self, info):
if self.StaticList == None:
print "Initializing ..."
self.StaticList = []
# Computationally expensive task to add elements to self.StaticList, depending on the value of parameter info
def data(self):
return self.StaticList
我從另一個腳本導入模塊,並有一個這樣的循環:
import myclass
for i in range(10000):
m = myclass.MyClass(i)
d = m.data()
# Do something with d.
靜態列表的初始化大約需要200到300毫秒,並且在循環的每次迭代中執行,因此循環需要很長時間才能完成。
雖然您的類確實有一個名為StaticList
的靜態字段,但實際上您正在初始化並使用同名的實例字段 ,因為您使用的是self
限定符。 我認為如果您使用MyClass.StaticList
來初始化和訪問它,您的代碼將正常工作。
通常,通過Python的名稱查找,您可以通過實例訪問類字段,就好像它是該實例上的實例字段(例如, self.StaticList
), 只要您實際上沒有設置同名的實例字段在那個例子上。 從那一刻起,實例字段會影響類字段(即, self.StaticList
將找到您的新值,而MyClass.StaticList
仍將引用您的類值)。
作為翻譯的新鮮例子:
>>> class A(object):
... v=2 # static initialization
...
>>> A.v
2
>>> a=A() # get an instance, and
>>> a.v # get the static value via the instance:
2
>>> a.v = 7 # but now set 'v' on the instance, and ...
>>> a.v # we will get the instance field's value:
7
>>> A.v # the static value is still the old:
2
>>> b=A() # and other instances of the class ...
>>> b.v # will use the same old static value:
2
實例變量av
最初等於Av
,但是通過明確設置av=7
,您在該實例中“解離”它們。
雖然這意味着,原則上,您可以使用靜態類字段MyClass.Values
以及同名的實例字段xyz.Values
,但通常不鼓勵這種混淆。
作為單獨的注釋,您可以考慮將data
方法注釋為@staticmethod
(並移除移動中的self
參數)並將其稱為MyClass.data()
以使事實更清楚,即您將返回相同的列表實例每次通話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.