King a écrit :
Python's getattr, setattr and __getattribute__ commands

s/commands/functions/

works fine
with python types.
For example:
print o.__getattribute__("name")

A very few corner cases set aside - the main one being inside a custom __getattribute__ method -, you should not directly access __getattribute__ (nor most __magic_methods__ FWIW).

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.

There's no "compound type" in Python. There are only objects, objects and objects.

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] ")

You can't (at least OOTB). the expression:

  gradient.colors[0][1]

is a shortcut for:

  colors = gradients.__getattribute__("color")
  colors_0 = colors.__getitem__(0)
  colors_0_1 = colors_0.__getitem__(1)

You can of course do something like

  g = getattr(o, "gradient")
  c = getattr(g, "colors")
  # etc...

but I guess this is not what you're after.

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.

I really don't think you need anything like this to serialize / unserialize your objects (whatever the format FWIW). You should really google for +python +serialize +XML, I bet you'd find at least a couple helpful articles on that topic.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to