Python OOP Problem

Martin v. Loewis martin at v.loewis.de
Mon Dec 28 07:29:26 EST 2009


Миклухо wrote:
> Hi, all. My problem is:
> 1) I have a database(postgresql)
> 2)I'm getting some string from database(string is a classname -
> written by me).
> 3)I need to construct new object from this string.
> In java it's done by Class.forName().newInstance();
> 
> For instance:
> 1)I receive the string: "MyObject".
> 2)o = MyObject();
> 3)o.myfunction();
> 
> Saw this link http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname,
> but it doesn't work for me. May be I do something wrong. I just
> started to learn python. Help, please.

In this case (you just started to learn Python), I recommend to take
an explicit approach. Create a dictionary that maps class names to
classes:

name2class = { "MyObject" : MyObject,
               "MyOtherObject" : MyOtherObject,
               "Etc" : Etc }

Then, when you receive the string class_name, you do

o = name2class[class_name]
o.myfunction()

HTH,
Martin



More information about the Python-list mailing list