Reflection in Python?

rdev at rdev at
Wed Jun 30 20:02:46 CEST 1999

In article <7ldglr$ita$1 at>,
  anders777 at wrote:
>  ...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
> 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?
If I understand what you are trying to do, it's
easy in Python.  Assuming MathTest is an
object instance:
test = MathTest.testAdd
will return you a bound method object which you
can then call as:
Getting the name of the object class and method
is also easy.  There are several ways to do this:
1) Define a doc string within the method by
   putting a quoted string as the first line
   under the def line.  You can then refer to it
   as "test.__doc__".  This could say, for
   example, "Method bar of class foo".
2) "test.__name__" will return the name of the
   method.  "test.im_class.__name__" will
   return the name of the class that the method
   is defined within.

class MathTest:
  def testAdd(self, parm1, parm2):
      "Method testAdd of Class MathTest"
      result = parm1 + parm2
      return result
<<< mt = MathTest()
<<< test = mt.testAdd
<<< print test.__doc__
Method testAdd of Class MathTest
<<< print test.__name__
<<< print test.im_class.__name__

I hope that helps.

- Roger

Sent via
Share what you know. Learn what you don't.

More information about the Python-list mailing list