Simple or Impossible in Python... dynamically dereferencing a class attribute

Bruce Wolk fake at not-a-real-address.net
Wed Dec 24 11:54:37 EST 2003


Bill Sneddon wrote:
> Given the following simple code.  I was trying find a way to
>  dynamically de-reference a class attribute.  Problem explained below.
> 
> 
> class test:
>      def __init__(self):
>          self.a = 0
>          self.b = 0
>          self.c = 0
> 
> myDict = {}
> myDict['one'] = test()
> myDict['two'] = test()
> 
> # I know I can do this at runtime.
> myVar = 7
> myDict['one'].a = myVar
> myLetter = 'b'
> 
> ## Is there any way to choose the attribute of test based on a varible.
> ## like this?
> 
> myDict['one'].{myLetter} = 9
> 
> I know you can do this kind of thing with other languages Perl, C++
> 
> Is it possible with Python?
> 
> If so what is the syntax in Python.
> 
> Maybe there is a better/equivalent approach if so could you point me
> to an example?
> 
something like...

setattr(myDict['one'],myletter,9)





More information about the Python-list mailing list