Dynamically creating attributes and methods

Ian Bicking ianb at colorstudy.com
Wed Oct 29 17:47:43 EST 2003


On Wednesday, October 29, 2003, at 04:24 PM, user at domain.invalid wrote:
> I'm writing a DBI for my company's database.
> I will have one class for each of the tables
> in the database.

You might want to try SQLObject (http://sqlobject.org) which will do 
this for you.

> I would then like each class, once instantiated,
> to be able to read the field list from it's table,
> and create properties based on each field, with
> get/set methods created for accessing.
>
> The get/set methods could be the same for every
> field, provided that I can determine the name
> of the field(property) being accessed.
>
> Given a field name such as 'phone', how can I
> give the class a home property, and then attach
> that property to the get/set methods on the fly?

But if not, you can use the __getattr__ and __setattr__ magic methods, 
or you can do something like:

getter = eval("lambda self: self._getColumn(%s)" % repr(colName))
setter = eval("lambda self, v: self._setColumn(%s, v)" % repr(colName))
prop = propert(getter, setter)
setattr(cls, colName, prop)


Where cls is your class, colName is the string name of the column, and 
you write _getColumn and _setColumn on your own.

--
Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org






More information about the Python-list mailing list