问题
I'm trying to create an IsDescription
subclass, so that I can define the structure of a table I'm trying to create. One of the attributes of the subclass** needs to be shaped given a certain length that is unknown until runtime (it depends on a file being parsed), but is fixed at runtime.
Sample code:
import tables
class MyClass(tables.IsDescription):
def __init__(self, param):
var1 = tables.Float64Col(shape=(param))
MyClass1 = MyClass(12)
Which returns: TypeError: object.__new__() takes no parameters
. Using self.var1 = ...
gives the same error.
In this SO question, the problem is listed as being because IsDescription
is a metaclass, but no reason is given why a metaclass would prohibit this behavior, and no workaround is given.
Is there a workaround to allow a table in PyTables to have unknown (but fixed) size?
Finally, to stave off XY problem comments, I think I could probably use an array or expandable array to do what I'm trying to do (which is output solution data to disk). I'm still curious to see answers to the questions above.
**They're called attributes in the PyTables docs, but writing >>> subclass.attrib
returns AttributeError: type object 'subclass' has no attribute 'attrib'
, so I don't know if that's the right word
回答1:
Use a dictionary to define the table instead of subclassing IsDescription
.
import tables
import numpy as np
param = 10
with tables.open_file('save.hdf','w') as saveFile:
tabledef = {'var1':tables.Float64Col(shape=(param))}
table = saveFile.create_table(saveFile.root,'test',tabledef)
tablerow = table.row
tablerow['var1'] = np.array([1,2,3,4,5,6,7,8,9,0])
tablerow.append()
table.flush()
with tables.open_file('save.hdf','r') as sv:
sv.root.test.read()
来源:https://stackoverflow.com/questions/20426152/how-can-the-shape-of-a-pytables-table-column-be-defined-by-a-variable