I have a python question that I’m sure is pretty simple – please feel free to disabuse me of any sort of bad practice while you’re at it. I have the following code:
class User(dict,BaseDBI):
def __init__(self,uid=None,username=None):
self['uid']=str(uuid())
if uid == None and username is not None:
uid_struct = self.Get('data/username.kch',username)
if uid_struct is not None:
self = self.Get('data/user.kch',uid_struct['uid'])
As you can tell this User is simply an extended dict object. It also accesses a few simple Get and Set methods on a couple of Kyoto Cabinet db files. I put in some print statements to trace through what’s going on and everything is being set properly, but when I create a User object (e.g.):
user = User(username='someusername')
and then print user I only have a new dict object that has the brand new uid generated by the first line under __init__
Thanks for any wisdom!
python variables are references. when you assign to
self, you are replacing that reference but not altering the object which is returned by__init__.The easiest thing may be to simply use the dict.update method to copy all key/value pairs into
self. This should ‘just work’ since you’re already inheriting from dict.Inheritance is only appropriate for a relationship like
A is a B. You indicate that a User is a dict, that’s fine, but I doubt that a User is a BaseDBI. It’s more likely that you want a User to have a database, in which case composition is more appropriate. This probably seems nit-picky, but will prevent you from making bizarre and obscene systems.