[Zope] More failed attempts with python
Paul Winkler
pw_lists at slinkp.com
Sat Aug 16 22:43:49 EDT 2003
On Sat, Aug 16, 2003 at 05:16:36PM -0700, Bill Hewitt wrote:
> Hello again folks...
> Below is what I have written in attempting to dynamically
> construct a variable name, then retrieve the value of the
> variable from the namespace in python.
(snip)
> newstring="%scolor" % (type)
fine...
> # Next I want to
> # retrieve the *value* for preferredcolor by evaluating the string I
> created in the variable newstring
> # I cant seem to get this to work......
> preferredcolor=container.newstring
There's your problem. You are literally asking for
an attribute of the container named "newstring".
What you want is:
getattr(container, newstring)
It's worth playing with this stuff in the python interpreter until you
really understand it. For example, see if you follow this:
$ python
Python 2.2.3 (#1, Jul 22 2003, 12:28:47)
[GCC 3.2.3 20030422 (Gentoo Linux 1.4 3.2.3-r1, propolice)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class C:
... def __init__(self):
... self.width = 10
... self.height = 2
...
>>> c = C()
>>> c.width
10
>>> c.height
2
>>> # So far so good.
>>> dimension = 'width'
>>> c.dimension
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: C instance has no attribute 'dimension'
>>> getattr(c, dimension)
10
>>> getattr(c, 'dimension')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: C instance has no attribute 'dimension'
>>>
--
Paul Winkler
http://www.slinkp.com
Look! Up in the sky! It's META FISHY SKORPION!
(random hero from isometric.spaceninja.com)
More information about the Zope
mailing list