Skip to main content
added 154 characters in body
Source Link
Wells
  • 11k
  • 16
  • 58
  • 93

Trying to instantiate a class based on a string value and... failing. 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.

How to resolve this? Update: I don't really want to use a mapping system: the names of these classes are defined INI files, and parsed that way, so they will be strings..

Trying to instantiate a class based on a string value and... failing. 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.

How to resolve this?

Trying to instantiate a class based on a string value and... failing. 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.

How to resolve this? Update: I don't really want to use a mapping system: the names of these classes are defined INI files, and parsed that way, so they will be strings..

Source Link
Wells
  • 11k
  • 16
  • 58
  • 93

python dynamic class names

Trying to instantiate a class based on a string value and... failing. 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.

How to resolve this?