Python OOP Problem

Миклухо mikluxo at gmail.com
Mon Dec 28 22:55:02 EST 2009


On 28 дек, 18:02, Daniel Fetchinson <fetchin... at googlemail.com> 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();
>
> Take a look at locals( ) and globals( ).
>
> The detailed answer depends on whether the class is defined in an
> imported module or is defined in the current namespace. From your
> example it seems the latter.
>
> Just in case it's the former, you could do this:
>
> import module_with_your_class
> astring = 'MyObject'
> o = getattr( module_with_your_class, astring )
>
> If the class is defined in the module where you are,
>
> class MyObject: pass
> astring = 'MyObject'
> o = locals( )[astring]( )
>
> If the class MyObject is not local, for example because you need 'o'
> in a function body, you can try globals( ) instead of locals( ).
>
> HTH,
> Daniel
>
> --
> Psss, psss, put it down! -http://www.cafepress.com/putitdown
Thanks for your reply. It's really helpful.
The hierarchy will be something like this(each file is a class):
           - RouterTable( where we take the string from db)
Router.py(the class which instantiates MyObject)
-- MyObject.py
 
-- MyObject2.py
 
-- MyObject3.py
Because each class should work independently from other and I cannot
stop my program when adding another Object.



More information about the Python-list mailing list