python dynamic class names

0 votes
I want to instantiate a class based on a string value but it's not working. The parser object below is a dict, in the example let's say we have one called foo and here parser['name'] is 'foo':

obj = parser['name']()
Fails, yielding TypeError: 'str' object is not callable. But, since I have:

class foo:
    def __init__(self():
        print 'Hello'
And if I do obj = foo() it works fine and creates the correct object. Also, calling obj = type(parser['name'])() doesn't work.

Can anyone tell me how to resolve this issue?
May 23 in Python by SDeb
• 11,080 points
11 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes
You can try the following code:

classmap = {
  'foo': foo
}

obj = classmap[parser['name']]()
answered May 23 by ana1504.k
• 6,830 points

Related Questions In Python

0 votes
1 answer

Python class inherits an object

Python 3.x: class MyClass(object): = new-style class class MyClass: ...READ MORE

answered Apr 17, 2018 in Python by anonymous
72 views
0 votes
1 answer

Python class inherits object

Python 3.x: class MyClass(object): = new-style class class MyClass: = new-style ...READ MORE

answered Aug 30, 2018 in Python by Priyaj
• 56,140 points
52 views
0 votes
1 answer

How does Python know whether a variable in the class is a method or a variable?

In python objects/variables are wrapped into methods ...READ MORE

answered Sep 18, 2018 in Python by ariaholic
• 7,320 points
31 views
0 votes
1 answer

“stub” __objclass__ in a Python class how to implement it?

You want to avoid interfering with this ...READ MORE

answered Sep 27, 2018 in Python by Priyaj
• 56,140 points
39 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
69 views
0 votes
1 answer

Access Webcam using Python?

OpenCV has support for getting data from ...READ MORE

answered Oct 17, 2018 in Python by ana1504.k
• 6,830 points
207 views
0 votes
1 answer

Power Math in Python

When you use "^" operator, it is ...READ MORE

answered Nov 12, 2018 in Python by ana1504.k
• 6,830 points
24 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.