2

***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'

6
  • do what? it really doesn't do anything useful. Commented Jun 16, 2011 at 4:41
  • I don't understand - your title says "creating instance from variable name", but it looks like you are trying to access testClass.test1. This is not an instance of the testClass class, and you aren't creating it. Commented Jun 16, 2011 at 5:06
  • I don't understand the edited question. 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? Commented Jun 16, 2011 at 5:42
  • yes. I'm trying to dynamically create an instance of a class from a variable of a string. Commented Jun 16, 2011 at 5:46
  • 2
    @jHoro, you'd better cut-and-paste rather than type your questions in. your examples never work as typed. Commented Jun 16, 2011 at 5:52

2 Answers 2

12

Instead of the eval(), you could say

getattr(locals()[x], y)

or

getattr(locals().get(x), y)

Is that what you mean?

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the answer. However I didn't phrase the question well. Please notice the edit.
1

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

1 Comment

But that is : "testClass" not testClass

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.