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, 2019 in Python by SDeb
• 13,300 points
958 views

1 answer to this question.

0 votes
You can try the following code:

classmap = {
  'foo': foo
}

obj = classmap[parser['name']]()
answered May 23, 2019 by ana1504.k
• 7,910 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
1,603 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
• 58,090 points
598 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 aryya
• 7,450 points
949 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
• 58,090 points
1,846 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,058 views
0 votes
1 answer
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,910 points
2,756 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,910 points
523 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP