Variable interpolation with getattr
Rich
google at moodring.com
Wed Feb 19 10:32:49 EST 2003
Andrew,
This looks interesting, but doesn't work for me inside the class,
such as within the constructor which can be use for initialization. I
think the post from Alex Martelli may have the key with __slots__ and
setattr, but this stuff isn't covered in detail in my "Learning
Python" book.
Thanks,
Rich
class C:
self.attr = ['city','state','zip']
def __init__(address)
for a in self.attr:
self.a = address[a]
^^
Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote in message news:<mailman.1045637395.17700.python-list at python.org>...
> On Tue, Feb 18, 2003 at 10:36:53PM -0800, Rich wrote:
> > Hello,
> >
> > 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
> > e.g
> >
> > 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
>
> It looks like you want is getattr:
> foo = getattr(self, x)
>
> e.g.:
> >>> class C:
> ... x = 1
> ...
> >>> name = 'x'
> >>> obj = C()
> >>> getattr(obj, name)
> 1
>
> -Andrew.
More information about the Python-list
mailing list