DISCLAIMER: This question is related to homework. I am not expecting a solution, but am hoping for a better understanding of what is being asked and the (possible) utility of this homework exercise.
This question was asked after a lesson on using Python's MySQLdb module and how to better represent the result set (and possibly its rows) instead of a tuple of tuples (as is default with MySQLdb).
The question is: Modify the classFactory.py source code so that the DataRow class returned by the build_row function has another method:
retrieve(self, curs, condition=None)
self is (as usual) the instance whose method is being called, curs is a database cursor on an existing database connection, and condition (if present) is a string of condition(s) which must be true of all received rows. The retrieve method should be a generator, yielding successive rows of the result set until it is completely exhausted. Each row should be a new object of type DataRow.
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
- What is the purpose of creating a class within a function definition? Is this commonly done by professional developers? If so, what is the benefit?
- Why is the database cursor an (explicit) argument of the
retrieve
method? Shouldn't the database cursor be referenced outside the scope of this script (when the database connection is made)? - Is it correct to say that (currently) the
build_row
function will accept two arguments -table
andcols
- and return a string that may look like (as an example) "exampleTable_record(fieldA, fieldB, fieldC)"? - When the
retrieve
method is successfully added, what should I expectbuild_row
to now return?
As I alluded to earlier, if I had an idea of why I'm being asked to add the retrieve
method, then I might have a better idea of how to attack this problem.