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
• 13,160 points
25 views

1 answer to this question.

0 votes
You can try the following code:

classmap = {
  'foo': foo
}

obj = classmap[parser['name']]()
answered May 23 by ana1504.k
• 7,870 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
127 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,900 points
75 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,340 points
52 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,900 points
58 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 289 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
• 7,870 points
418 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
• 7,870 points
42 views