getattr() question
Sledge
andrew.j.sledge at gmail.com
Sat Dec 22 18:39:34 EST 2007
Hi.
I am trying to dynamically load a class and attributes at run time. I
do not know what classes will be referenced until run time. I have it
loading the module correctly, but when I use getattr to access the
class and its attributes everything works except that I get additional
unwanted output. The code
testclass.py:
#!/usr/bin/python
class testclass(object):
myname = ""
def __init__(self, name):
self.myname = name
def view(self):
print "hello %s" % self.myname
test.py:
#!/usr/bin/python
import sys
sys.path.append('.')
from pprint import pprint
if __name__ == '__main__':
myname = "testclass"
myaction = "view"
try:
tc = __import__(myname)
myclass = getattr(tc,myname)
myinstance = getattr(myclass('python n00b'), myaction,
myaction)
pprint(myinstance())
except ImportError:
"error"
Here is the output that I get:
user at debian:~/$ python test.py
hello python n00b
None
user at debian:~/$
Why is it printing 'None'? What am I doing wrong. I appreciate any
help.
More information about the Python-list
mailing list