Simple or Impossible in Python... dynamically dereferencing a classattribute

B

Bill Sneddon

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?
 
B

Bruce Wolk

Bill said:
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)
 
M

Michael Cornelius

Bill said:
Given the following simple code. I was trying find a way to
dynamically de-reference a class attribute.

Have a look at getattr/setattr.
'foo'
 
B

Bill Sneddon

Bruce Wolk wrote:

something like...

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

This works!!! sorry for wasting bandwidth with such an easy question.
but thank you for your answer.
Merry Christmas!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top