在python 2.7中,我想創建一個靜態變量來存儲運行封閉類的靜態方法的結果。參考靜態變量的靜態方法
我試過如下:
class A:
@staticmethod
def foo():
return 1
v = A.foo() # a static variable
print A.v
返回錯誤:
NameError: name 'A' is not defined
然而,參考其他類的靜態變量的作品:
class B:
@staticmethod
def foo():
return 1
class A:
@staticmethod
def foo():
return 1
v = B.foo()
print A.v
>>> 1
任何解釋嗎?
編輯:
用例的這個場景是緩存foo的結果,並且在A的名字空間括起來。 接下來的答案我明白,A尚未定義在執行時,這會導致錯誤。 我想出了以下延遲計算:
class A:
@staticmethod
def foo():
print 'running foo'
return 1
@staticmethod
def get_v():
try:
return A.v
except AttributeError:
A.v = A.foo()
return A.v
print A.get_v()
print A.get_v()
>>> running foo
>>> 1
>>> 1
這似乎做的工作,但稍顯麻煩。
那時'A'甚至不存在,因此錯誤。 –
你能解釋一下你爲什麼要這樣做嗎?僅僅是爲了緩存目的? –
在這個例子中,你會想把'foo()'移到類的外面並使之成爲一個函數,但是我懷疑你想做更復雜的事情。 – BlueTrin