***EDIT2: Sorry about the broken code. Here is working code which illustrates the same issue:
class bead():
def printmsg(a):
print('test message')
chain1=bead()
x='chain1'
eval(x + '.printmsg()')
***EDIT: Thank you gnibbler for answering the original question. Here's a better worded version of my question:
class bead():
def msg():
print('test message')
x='chain1'
y='bead1'
eval(x + '.' + y + '=bead()')
chain1.bead1.msg()
output: 'test message'
What's a better way to do that?
Original question:
script:
class testClass():
test1='test1 text'
x='testClass'
y='test1'
eval(x + '.' + y)
output: 'test1 text'
Is there a better way of doing this?
***EDIT: getattr() works for pulling the information from the class. Thank you gnibbler. Let me change the question a little bit though:
what could I use instead of:
x='chain1' y='mol1'
2 Answers 2
Instead of the eval(), you could say
getattr(locals()[x], y)
or
getattr(locals().get(x), y)
Is that what you mean?
1 Comment
I think I understand. What you probably want is:
>>> class testClass():
... test1='test1 text'
...
>>> getattr(testClass, 'test1')
'test1 text'
Still that isn't creating an instance. Riffing on gnibbler's answer, here you make an instance:
>>> locals().get(x)()
<__main__.testClass instance at 0xb73b056c>
>>> getattr(locals().get(x)(), y)
'test1 text'
For your latest edit:
>>> class bead():
... def printmsg(a):
... print('test message')
...
>>> chain1=bead()
>>> x='chain1'
>>> eval(x + '.printmsg()')
test message
>>> getattr(locals()[x], 'printmsg')()
test message
testClass.test1. This is not an instance of thetestClassclass, and you aren't creating it.eval(x + '.' + y + '=bead()')doesn't work. You can't do an assignment in there. Are you asking for a way to dynamically create variables or are you asking something about the class?