[Tutor] Dynamically calling a class
jfouhy@paradise.net.nz
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:
> doingsomething
> class B:
> doing something
>
> for x in list_of_classes:
> x()
>
> 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:
... pass
...
>>> class B:
... pass
...
>>> class C:
... pass
...
>>> classes = [A, B, C]
>>> for cls in classes:
... x = cls()
... print x.__class__
...
__main__.A
__main__.B
__main__.C
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.
--
John.
More information about the Tutor
mailing list