dynamic creating of class

Gerhard Häring gh at ghaering.de
Sat Jun 21 12:15:47 EDT 2003


Salvatore wrote:
> Jaros?aw Zabie??o wrote:
> 
>> Is there a possibility for Python to dynamic binding of class?  I can
>> do it in PHP but I do not know how to make the same in Python. Look at 
>> the following example:
> 
> 
> I had the same problem and I don't remember who gave me the solution.
> The idea is to use 'eval'
> 
> class A:
>     def __init__(self):
>         self.class_name = 'A'
> 
> class B:
>     def __init__(self):
>         self.class_name = 'B'
> 
> 
> choosed_class = 'A'
> choosed_class += '()'
> instance_of_choosed_class = eval(choosed_class)
> 
> Thanks to the one who gave me the solution :-)

While this works, hee's a better solution:

chosen_class = A
instance_of_chosen_class = chosen_class()

Classes are just yet another type of object :)

-- Gerhard





More information about the Python-list mailing list