Reflection in Python?
Michael Hudson
mwh21 at cam.ac.uk
Wed Jun 30 13:32:47 EDT 1999
anders777 at my-deja.com writes:
> I've just started programming in Python, and I
> could really use some help figuring out something.
> I'd like to implement Kent Beck's unit tester in
> Python (someone posted a very nice alternative a
> few weeks ago, but Junit's approach works better
> for my project's needs). How do I do the
> equivalent of what Java calls reflection? I want
> to do the following:
>
> test = MathTest("testAdd")
>
> where test.run() will run the "testAdd" method on
> the MathTest object? I also want to be able to
> tell the user the name of the object (MathTest)
> and the method in case the method fails. Any
> thoughts?
>
> Thanks,
> Anders Schneiderman
> National Journal Daily Briefings Group
>
Not entirely sure I follow, but will this do what you want?
class Test:
def __init__(self,object,meth):
self.object = object
self.meth = meth
def run():
try:
getattr(self.object,self.meth)()
except:
print self.object.__class__.__name__, "failed!"
then
test = Test(MathTest,"testAdd")
test.run()
does what you ask (I think).
Anyway, I suspect the builtin "getattr" is what you're after.
HTH
Michael
More information about the Python-list
mailing list