Dynamically creating attributes and methods

John Roth newsgroups at jhrothjr.com
Wed Oct 29 17:54:06 EST 2003


<user at domain.invalid> wrote in message
news:a783b99c09d1dabeb8dbc9841103767c at news.teranews.com...
> Hi,
>
> I'm writing a DBI for my company's database.
> I will have one class for each of the tables
> in the database.
>
> 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?
>
> Thanks,
>
> Toby

The easiest method to understand is to build
the desired method in a string and use exec() to
create a function object. Then use setattr() to
insert the function object into the class object.
Then you can create the property object and
insert it into the class the same way.

John Roth
>






More information about the Python-list mailing list