我使用h5py訪問HDF5文件並將h5py File對象存儲在類中。但我經歷試圖重新分配一個新的封閉h5py文件實例變量的一些奇怪的行爲:以h5py對象作爲實例變量的複雜賦值行爲
class MyClass:
def __init__(self, filename):
self.h5file = None
self.filename = filename
def vartest(self):
self.h5file = h5py.File(self.filename, 'r')
print self.h5file
self.h5file.close()
print self.h5file
newh5file = h5py.File(self.filename, 'r')
print newh5file
self.h5file = newh5file
print self.h5file
print newh5file
def main():
filename = sys.argv[1]
mycls = MyClass(filename)
mycls.vartest()
輸出:
<HDF5 file "test.h5" (mode r, 92.7M)>
<Closed HDF5 file>
<HDF5 file "test.h5" (mode r, 92.7M)>
<Closed HDF5 file>
<Closed HDF5 file>
嘗試更新與新開h5py實例變量文件對象似乎以某種方式影響了對象的狀態,關閉它。無論在h5py方面的實現如何,我都沒有看到這種行爲從我對Python語言的理解(即賦值運算符沒有超載)中是否有意義。
本例使用Python 2.6.5和h5py 1.3.0運行。如果你想嘗試這個例子,但是沒有圍繞着HDF5文件,你可以將文件訪問模式從'r'改爲'a'。
如果您註釋掉'self.h5file = newh5file'行,它會打印「關閉」嗎? 'self.h5file' a [屬性](http://docs.python.org/library/functions.html#property)? 'h5py.File()'是否保持一些全局狀態? – jfs
如果我註釋掉'self.h5file = newh5file',有趣的是'newh5file'和'self.h5file'(我明確關閉)顯示爲正在打開''。該示例是獨立的,self.h5file不是屬性。我不能告訴你很多關於'h5py.File()'的實現,如果有一些全局狀態,我不會感到驚訝,但我不明白如何簡單地分配一個實例變量改變全局狀態(某人正在做引用計數的地方?)。 –