From: brian z. <bz...@zi...> - 2001-04-21 14:14:49
|
Scott, Here's an example of what I think you are looking for (it works equally well on a [Java|Python] [class|instance]: >>> class Test: ... def go(self): ... print "invoked go" ... def went(self): ... print "invoked went" ... >>> t = Test() >>> dir(t.__class__) ['__doc__', '__module__', 'go', 'went'] >>> for a in dir(t.__class__): ... if a[0:2] <> "__": ... getattr(t, a)() ... invoked go invoked went >>> Notice the line: getattr(t, a)() The built-in 'getattr' retuns a method bound on the instance t, similar to a Method object in Java. In Java, to execute the Method, you would call: m.invoke(instance, params) in Python you use the callable nature of objects and invoke it by: m(params) since the method is already bound to the instance you don't need to pass it as a param as you do in Java since in Java the Method is always bound to the class, not an instance. For a more indepth look at when the method is bound to an instance and when to a class: >>> getattr(Test, "go") <unbound method Test.go> >>> getattr(t, "go") <method Test.go of Test instance at 3335245> >>> getattr(Test, "go")(t) invoked go >>> getattr(t, "go")() invoked go >>> Notice that when I get the method from the class, I need to pass an instance to invoke it, fulfilling the contract for sending a 'self' argument. Also note that neither go() or went() required arguments in my example. If you really want to blindly invoke methods you'll need to figure out if they require arguments. In general, the invoker knows the arguments required, such as the callback in os.path.walk(). You might want to check out this as well: http://www.diveintopython.org/apihelper_getattr.html hope this helps, brian > -----Original Message----- > From: jyt...@li... > [mailto:jyt...@li...]On Behalf Of Scott > Knight > Sent: Saturday, April 21, 2001 7:52 AM > To: jython > Subject: [Jython-users] Running auto-discovered methods > > > A few days ago, Neil Benn queried "Self Describing Scripts in Jython" > and appears to be wanting to do something similar to what I need: > something analogous to Java's Reflection. I can easily get a list of > the method names in a class. I can't figure out how to invoke the > method given it's name in string form. What I am really after is to > cycle through all of the method names in the list and run them all, > rather than type up a method that calls each of a couple hundred methods > statically. > -- > Scott Knight mailto:sc...@sc... > http://www.scottknight.com/ > > _______________________________________________ > Jython-users mailing list > Jyt...@li... > http://lists.sourceforge.net/lists/listinfo/jython-users |