The next method we look at is the constructor—the __init__()
method. It will be used to create individual instances of an entity. The constructor can be called in two ways:
With a single
id
argument, in which case, an existing record will be retrieved from the database and the instance initialized with the column values of this record, orWith a number of keyword arguments to create a new instance and save this as a new database record
The code to implement this behavior looks like the following:
Chapter5/entity.py
def __init__(self,id=None,**kw): for k in kw: if not k in self.__class__.columns : raise KeyError("unknown column") cursor=self.threadlocal.connection.cursor() if id: if len(kw): raise KeyError("columns specified on retrieval") sql="select * from %s where %s_id = ?"%( self.__class__.__name__,self.__class__.__name__) cursor.execute(sql,(id,)) entities=cursor.fetchall() if len(entities)!=1 : raise...