Reflection in Python?
rdev at my-deja.com
rdev at my-deja.com
Wed Jun 30 13:59:45 EDT 1999
In article <7ldglr$ita$1 at nnrp1.deja.com>,
anders777 at my-deja.com wrote:
> ...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?
>
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:
test()
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.
Example:
class MathTest:
def testAdd(self, parm1, parm2):
"Method testAdd of Class MathTest"
result = parm1 + parm2
return result
<<< mt = MathTest()
<<< test = mt.testAdd
<<< test.run(2,2)
4
<<< print test.__doc__
Method testAdd of Class MathTest
<<< print test.__name__
testAdd
<<< print test.im_class.__name__
MathTest
I hope that helps.
- Roger
> Thanks,
> Anders Schneiderman
> National Journal Daily Briefings Group
>
> Sent via Deja.com http://www.deja.com/
> Share what you know. Learn what you don't.
>
Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
More information about the Python-list
mailing list