Python OOP Problem

Миклухо mikluxo at gmail.com
Mon Dec 28 23:16:13 EST 2009


On 28 дек, 18:29, "Martin v. Loewis" <mar... at v.loewis.de> wrote:
> Миклухо 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 linkhttp://stackoverflow.com/questions/452969/does-python-have-an-equival...,
> > 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

Thanks for reply, but it doesn't fit to my task. If I will add later
other objects(and it will be very often) - I should stop the service,
but that would be very bad.
I'm not sure, if this is solution, but test passed:

myimportmod = __import__('ClassName', globals(), locals(),
['ClassName'], -1)
mod = getattr(_myimportmod, 'ClassName')
o = mod();
o.myfunction();



More information about the Python-list mailing list