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

Jean Brouwers JBrouwersAtProphICyDotCom at no.spam.net
Tue Jul 27 08:05:05 CEST 2004


This may work.

<pre>

  class Dyn:
      '''Dynamic class.
      '''
      def __init__(self, **kwds):
          self.set(**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
  c.set(a4=4, a5=5)

   # attr can be changed
  c.a1=10
  c.set(a1=20)

</pre>

/Jean Brouwers




In article <nblNc.19344$QO.6564 at bignews5.bellsouth.net>, Robert Oschler
<no_replies at fake_email_address.invalid> wrote:

> Hello,
> 
> 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
> 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.
> 
> Thanks



More information about the Python-list mailing list