Reflection in Python?

Michael Hudson Michael.Hudson at
Wed Jun 30 15:32:47 EDT 1999

From: Michael Hudson <mwh21 at>

anders777 at 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 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():
            print self.object.__class__.__name__, "failed!"


test = Test(MathTest,"testAdd")

does what you ask (I think).

Anyway, I suspect the builtin "getattr" is what you're after.


More information about the Python-list mailing list