Dynamically create a class (or class instance) and its attributes?

Christopher T King squirrel at WPI.EDU
Tue Jul 27 16:48:04 CEST 2004


On Tue, 27 Jul 2004, Robert Oschler wrote:

> For example, given a MySQL row object from a fetchone() call:
> 
> employee_name = sqlrow[field_dict['empname']]
> 
> To make the syntax easier and clearer, I would like to create a Python class
> instance that would allow me to access the fields in the MySQL row as
> attributes of a class created dynamically from the row structure. For
> example:
> 
> employee_name = ez_sqlrow.empname
> 
> What would be the best way to create such a class or class instance?  Any
> code examples you have would be welcome.

The other respondents have recommended using setattr(), but here's a way 
that will work completely dynamically:

 class ez_sql(object):

     def __init__(self,sqlrow):
         self._sqlrow = sqlrow

     def __getattr__(self,a):
         try:
             return self._sqlrow[fielddict[a]]
         except (IndexError,KeyError),e:
             raise AttributeError,e

     def __setattr__(self,a,v):
         try:
             self._sqlrow[fielddict[a]] = v
         except KeyError:
             self.__dict__[a] = v

This is a bit slower than using setattr(), but might save a good deal of 
memory (especially if you keep the SQL rows around in another form).




More information about the Python-list mailing list