Variable interpolation or indirection for instance attributes
Andrew Bennetts
andrew-pythonlist at puzzling.org
Wed Feb 19 02:00:39 EST 2003
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