Dynamically creating properties?

John Gordon gordon at panix.com
Thu Oct 27 16:14:47 EDT 2011


In <a47fb589-520a-49ec-9864-cac1d7ea11eb at s9g2000yqi.googlegroups.com> Andy Dingley <dingbat at 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
gordon at panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"




More information about the Python-list mailing list