Dynamically create a class (or class instance) and its attributes?
JBrouwersAtProphICyDotCom at no.spam.net
Tue Jul 27 08:05:05 CEST 2004
This may work.
def __init__(self, **kwds):
def set(self, **kwds):
for a, v in kwds.iteritems():
setattr(self, a, v)
# all attr defined at creation
# time with an initial value
c = Dyn(a1=1, a2=2, a3=3)
# more attr can be added
# attr can be changed
In article <nblNc.19344$QO.6564 at bignews5.bellsouth.net>, Robert Oschler
<no_replies at fake_email_address.invalid> wrote:
> I am a Python newbie (by experience, not chronologically :) ), so if any of
> this doesn't make sense my apologies in advance.
> I am reading the chapter in The Python Cookbook on databases and the MySQLdb
> module. In it they show an example of a recipe that lets you access fields
> in a MySQL row by name rather than by column number. 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
> 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.
More information about the Python-list