How to access object attributes given a string

Chris cwitts at gmail.com
Tue Feb 12 15:31:10 EST 2008


On Feb 12, 10:25 pm, Santiago  Romero <srom... at gmail.com> wrote:
>  Hi...
>
>  I'm trying to guess how to access attributes of an existing object
> given the attribute name in a string. I mean:
>
> class Object:
>     self.x = 12
>     self.y = 20
>     self.name = "blah"
>
> def ChangeAttribute( object, attribute, value ):
>   # Insert here the code for object.attribute = value
>   XXXXX
>
>  Allowing this kind of calls:
>
>  ChangeAttribute( object, "x", 200 )
>  ChangeAttribute( object, "name", "my name" )
>
>  Thanks.
>
> PS: I need it for a concrete case in a game scripting language I'm
> writing, so that I can call functions like "CHANGE_PLAYER_VALUES( "x",
> 100 )".

   help(setattr)

Help on built-in function setattr in module __builtin__:

setattr(...)
    setattr(object, name, value)

    Set a named attribute on an object; setattr(x, 'y', v) is
equivalent to
    ``x.y = v''.



More information about the Python-list mailing list