Emulating a = x.y and x.y = a, when 'y' is a string
bruce_deletethis_dawson at cygnus-software.com
Thu Oct 17 07:31:26 CEST 2002
I want to do dynamic access to member variables in Python - reading from
and writing to object member variables based on a member name stored in
a string. If the member is stored in __dict__ it is easy enough, but
what if it is emulated with __getattr__, or a property, or __getattribute__?
exec() gives the same behavior, but can cause bad performance if you do
it a lot, because it has to compile the code. Is there any way to get
Python to do exactly the same thing as x.y = a and a = x.y, when the
member name is a string.
The following functions work well enough for normal member variables -
is there a canonical way of doing this in the generic case?
def GetMemberVariable(object, attributeName):
def SetMemberVariable(object, attributeName, newValue):
object.__dict__[attributeName] = newValue
# Sample usage:
a = GetMemberVariable(x, "y")
SetMemberVariable(x, "y", 0)
Thanks for any help.
More information about the Python-list