In <a47fb589-520a-49ec-9864-cac1d7ea1...@s9g2000yqi.googlegroups.com> Andy 
Dingley <ding...@codesmiths.com> writes:

> How can I dynamically generate properties (or methods) and add them to
> my class?  I can easily produce a dictionary of the required element
> names and their text values, but how do I create new properties at run
> time?

You can set dynamic attributes on class objects without any special
processing at all.  Just do it, like so:

  class X(object):
    pass

  myx = X()

  myx.color = 'red'
  myx.food = 'french fries'
  myx.lucky_number = 7

Or, if you don't know the attribute name beforehand:

  setattr(myx, 'occupation', 'programmer') 

For methods, use an existing method name (without the trailing parentheses)
as the attribute value, like so:

  myx.method = float # assigns the built-in method float()

-- 
John Gordon                   A is for Amy, who fell down the stairs
gor...@panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to