general class functions

S

syd

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'
 
S

Steven Bethard

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


Does this work for you?
.... pass
.... 'C'

Steve
 
S

syd

Thanks for everyone's help on this thread. Right now, I've got a
general class ("Container") holding items that can be accessed by item
attribute values through __getattr__ functions.

My various classes use Container as a subclass. Right now, I keep both
classes in the same file, and everything works great. However, when I
move Container to a separate file and "from myClasses import Container"
to use this general class, I seem to lose all of the __getattr__
functionality while retaining the other functions in Container.
Does anyone know why this happens and how I can get around this??
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,212
Messages
2,571,101
Members
47,695
Latest member
KayleneBee

Latest Threads

Top