Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #15058

Re: Dynamically creating properties?

From John Gordon <gordon@panix.com>
Newsgroups comp.lang.python
Subject Re: Dynamically creating properties?
Date 2011-10-27 20:14 +0000
Organization PANIX Public Access Internet and UNIX, NYC
Message-ID <j8ce3m$g7g$1@reader1.panix.com> (permalink)
References <a47fb589-520a-49ec-9864-cac1d7ea11eb@s9g2000yqi.googlegroups.com>

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Dynamically creating properties? Andy Dingley <dingbat@codesmiths.com> - 2011-10-27 12:59 -0700
  Re: Dynamically creating properties? John Gordon <gordon@panix.com> - 2011-10-27 20:14 +0000
  Re: Dynamically creating properties? DevPlayer <devplayer@gmail.com> - 2011-10-27 14:48 -0700
    Re: Dynamically creating properties? DevPlayer <devplayer@gmail.com> - 2011-10-27 16:00 -0700
      Re: Dynamically creating properties? DevPlayer <devplayer@gmail.com> - 2011-10-27 16:15 -0700
        Re: Dynamically creating properties? DevPlayer <devplayer@gmail.com> - 2011-10-27 17:35 -0700
      Re: Dynamically creating properties? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-10-28 07:42 +0000
        Re: Dynamically creating properties? DevPlayer <devplayer@gmail.com> - 2011-10-30 07:11 -0700
    Re: Dynamically creating properties? Lie Ryan <lie.1296@gmail.com> - 2011-10-28 14:42 +1100

csiph-web