Confused about hasattr/getattr/namespaces
Brian Roberts
brian at mirror.org
Sun Feb 29 13:48:21 EST 2004
I'm confused about the use of hasattr/getattr, or possibly
namespaces. I know how to do this:
class UnderstandThis(object):
def do_foo(self): pass
def do_bar(self): pass
def doit(self, cmd):
funcname = 'do_' + cmd
if hasattr(self, funcname):
getattr(self, funcname)()
else:
print 'not found'
But if I try to do this with classes in a module (instead of
functions in a class):
class FooGenerator(object): ...
class BarGenerator(object): ...
def generate(cmd):
clsname = cmd + 'Generator'
if hasattr(???, clsname):
etc...
I don't know what to use for ??? instead of self. If I print
globals() inside generate() it shows the two classes, but using
it in the hasattr line doesn't work -- huh? I can make it work
by wrapping the generate function in a (otherwise useless) class
and using self -- again, huh?
Couldn't find an explanation or example in the docs. In fact,
the description of vars/globals/locals (in section 2.1) just
confused me even more. Think I'm heading down the wrong path.
Can somebody please un-confuse me?
Brian.
More information about the Python-list
mailing list