[Tutor] Dynamically calling a class
jfouhy at paradise.net.nz
Fri Jun 10 02:12:41 CEST 2005
Quoting Ryan Parrish <ryanpublic at foxracing.com>:
> example -
> list_of_classes = ['A', 'B', B', 'A']
> class A:
> class B:
> doing something
> for x in list_of_classes:
> my problem is that i get 'TypeError: 'str' object is not callable', of
> which i understand what the error is saying, i just want to know how to
> dynamically call the class.
Just put the class object in the list!
>>> class A:
>>> class B:
>>> class C:
>>> classes = [A, B, C]
>>> for cls in classes:
... x = cls()
... print x.__class__
You can do some black magic to go from the string 'A' to the class A (eg, use
eval()), but it's generally better to avoid that if you can.
More information about the Tutor