The code below works (it will eventually pull records from a database via SQL), but I am having trouble understanding why the assert statement in the code below works.
def build_row(table, cols):
"""Build a class that creates instances of specific rows"""
class DataRow:
"""Generic data row class, specialized by surrounding function"""
def __init__(self, data):
"""Uses data and column names to inject attributes"""
assert len(data)==len(self.cols)
for colname, dat in zip(self.cols, data):
setattr(self, colname, dat)
def __repr__(self):
return "{0}_record({1})".format(self.table, ", ".join(["{0!r}".format(getattr(self, c)) for c in self.cols]))
DataRow.table = table
DataRow.cols = cols.split()
return DataRow
When is the length of 'data' determined and how is it guaranteed to be the same length as 'self.cols'? Will someone please explain this behavior?
setattr(self, colname, dat)instead of usingdata.()to callcols.split()otherwise your code won't work