Get attribute this way

Chris Rebert clp2 at rebertia.com
Tue Nov 17 01:35:43 EST 2009


On Mon, Nov 16, 2009 at 10:04 PM, King <animator333 at gmail.com> wrote:
> Python's getattr, setattr and __getattribute__ commands works fine
> with python types.
> For example:
> print o.__getattribute__("name")
> print getattr(o, "name")
> This is the easiest way to get an attribute using a string.
>
> In my case the "Node" class load/creates all the attributes from a xml
> file.
> Example
> <Input name="position" type="float" value="0.5"/>
> <Input name="color" type="color" value="0,0,0"/>
>
> There are certain atrributes of compound type.
> Example:
> # Array of colors, Here we are referring first color and second element
> (green)
> self.gradient.colors[0][1] = 0.5
> # Array of floats, referring first element
> self.gradient.positions[0] = 1.0
>
> Color, color array and floats are all custom classes.
>
> Now question is how to get these compound attributes using string as
> we do with default singular attributes.
> Example:
> getattr(o, "gradient.colors[0][1] ")
> I need this to save the data of nodes->attributes into a custom xml
> format, when loading this data back, I create the node first and then
> setup values from the saved xml file.

Can't you just iterate over the data structure? I'm not seeing why
you'd need to use getattr() and friends in the first place.

for color in self.gradient.colors:
    for element in color:
        #output XML fragment

#repeat for self.gradient.positions, etc.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list