On Tue, 2007-04-10 at 17:50 -0500, Jeremy Dunck wrote:
> On 4/10/07, Grupo Django <[EMAIL PROTECTED]> wrote:
> >
> > I know this is not the right place for asking about python, but it's a
> > simple question.
> > I need to load an object given in a string. Example:
> >
> > #I have a class called foo
> > class foo:
> >     def Hello():
> >         return "Hello World"
> >
> > object = 'foo'
> >
> > print object.Hello()
> 
> You probably don't really want to use the variable name "object",
> since that's also the name of Python's base class.
> 
> But just to follow your example, these lines (almost) do what you want:
> 
> object = foo()
> print object.Hello()
> 
> Now I'll rewrite it using better Python conventions and correct a small bug:
> 
> class Foo(object):
>     def hello(self):
>         return "Hello World"
> 
> o = Foo()
> print o.hello()
> 
The key is that he wanted to use the string name of the class, not the
class itself. Assuming that Foo is available (i.e., is local to the code
you're running or has been imported), this should work:

o = locals()['Foo']()

The locals() function returns a dictionary with all currently defined
names as keys mapped to their current values. Since 'Foo' is mapped to a
class, the code above gets the class and then makes an instance by
calling it like a function.

Todd


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to