Variable interpolation or indirection for instance attributes

Rich google at
Wed Feb 19 07:36:53 CET 2003


New to Python with a Perl background, and I've searched a good bit on
this and can't seem to find the answer.  I'd like to know if it is
possible to use a variable to hold the name of an instance attribute 

     x = 'street'
self.x = '123 Albermarle Street'

such that x in self.x gets evaluated to 'street' and thus self.x
becomes actually self.street.  I've seen a number of (possibly
outdated) language proposals about backticks and $ symbols. None of
these seem to work including (self.x), $self.x, self.$x, self.x$,
`self.x`, etc.  I did see an external library mentioned that had a
short perhaps 4 character name begining with an 'i' like 'itrp', but
I'm stubbornly thinking that there must be a way within the language
to do it.

At the same time, I'd like to find a way to initialize many class
instance attribuites from a passed in dictionary, without just
creating a dictionary as a n instance attribute.  And I really want to
beat this dead horse to understand whether or not these things are
possible, even if there is another way!

A more likely example:

 class Address:

  def __init__(self,address=''):

      self.props = ['extended','street','locality','region','postalcode']
      self.extended = ''
      self.street   = ''
      self.locality = ''
      self.region   = ''

      if address:
        for addresspart in address.keys():
          self.(addresspart) = address[addresspart]    # whishful
  def __getitem__(self,i):
    key = self.props[i]
    return eval(self.key)                              # same here

Any thoughts


More information about the Python-list mailing list