two new wrinkles to the general class!

syd syd.diamond at gmail.com
Fri Nov 5 08:32:21 EST 2004


Good thinking!  I'll give my take on the two suggestions below...

>     desired_class = globals()[desired_empty_class_string]
>     myobject = desired_class()

I understands your hesitation about using this, although this is
relatively more portable in that you don't need to have the dictionary
passed around.  One limitation is subclassing, ie, you could not do
globals()['Library.Nation_A']. You can get around this by splitting the
string by '.' and recursively using getattr() to get subclasses in your
split list.

>     LibraryFactory = { 'Library': Library, 'Nation_A':Nation_A, ... }

>     myobject = LibraryFactory[desired_empty_class_string]()

This works well, too, as long as you define this outside the classes
after you've defined everything.  This limits portability a bit though,
because you a 'from myClasses import Library' would not grab the
LibraryFactory.

--------------------------------------------------
On a related note, is there a good way from within a class to get the
name in the simple form?  Ie,

# str(library.__class__)
"<class 'foo2.Library'>"

I'm looking for something more along these lines:
# hypotheticalMethod(library)
'Library'




More information about the Python-list mailing list