dynamic creating of class

Lee Harr missive at frontiernet.net
Sat Jun 21 11:04:41 EDT 2003


In article <ulj8fvcs6483dh7khpl6jm6fsu26snnjv1 at 4ax.com>:
> 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:
> 
> #PHP:
><?php
> class A {
>     var $x = 'class A';
> }
> class B {
>     var $x = 'class B';
> }
> $kind = 'B';
> $run = new $kind(); # IT WORKS!
> print $run->x;
> ?>
> 
> #Python:
> class A:
> 	x = 'class A'
> class B:
> 	x = 'class B'
> kind = 'B'
> run = kind() # IS DOES NOT WORK :(
> print run.x



maybe something like this might help:

class A:
    def __init__(self):
        self.name = 'A instance'

class B:
    def __init__(self):
        self.name = 'B instance'

my_class_list = [A, B]
my_class_dict = {'A': A, 'B': B}

a_choice = 'A'
b_choice = 'B'

instance0 = my_class_list[ord(a_choice) - ord('A')]()
instance1 = my_class_dict[b_choice]()

print instance0.name
print instance1.name





More information about the Python-list mailing list