[英]Perplexing assignment behavior with h5py object as instance variable
我正在使用h5py访问HDF5文件并将h5py File对象存储在类中。 但是我试图用一个新的重新分配一个封闭的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 File对象更新实例变量似乎以某种方式影响了对象的状态,关闭它。 无论h5py方面的实现如何,我都没有看到这种行为对我的Python语言的理解是有意义的(即,没有赋值运算符的重载)。
此示例使用Python 2.6.5和h5py 1.3.0运行。 如果你想尝试这个例子,但没有HDF5文件,你只需将文件访问模式从'r'更改为'a'即可。
不确定这是否有帮助,但搜索源代码我发现这个(缩写):
class HLObject(object):
def __nonzero__(self):
register_thread()
return self.id.__nonzero__()
class Group(HLObject, _DictCompat):
...
class File(Group):
def __repr__(self):
register_thread()
if not self:
return "<Closed HDF5 file>"
return '<HDF5 file "%s" (mode %s, %s)>' % \
(os.path.basename(self.filename), self.mode,
_extras.sizestring(self.fid.get_filesize()))
因为没有__str__
方法, __repr__
调用__repr__
来产生输出, __repr__
首先调用register_thread()
,然后检查self
是否存活(更好地称为评估为True或False)。
然后Python搜索类,直到它找到__nonzero__
(再次调用register_thread()
),然后返回self.id.__nonzero__()
,这显然返回False。
所以,你是正确的,因为问题不在于名称绑定(赋值),而是为什么register_thread
和/或self.id
正在轰炸你,我不知道。
是的,这是h5py 1.3中的已知错误,当您使用HDF5 1.8.5或更高版本时会显示该错误。 它与1.8.5中标识符处理方式的变化有关。 您可以使用HDF5 1.8.4或更早版本或升级到h5py 2.0来修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.