From: Kevin B. <kb...@ca...> - 2001-09-04 17:44:17
|
Humbel Otmar wrote: > > [ John Goerzen ] > > > > Another question (sorry about all of these!) > > > > I'm porting more Java code to Jython. I've got a case like: > > > > public static String myfunc(String id) > > > > I'm unsure how to do a static method in Jython. Do I declare it in my > > .py oustide the class: area with a @sig that has static in it? > > Just inside the class, but **without** the self parameter. Given file > Foo.py: No - this does _not_ work in any version of Python/Jython I've used: Jython 2.1a1 on java1.3.0 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> class X: ... def go( id ): ... print "called:", id ... >>> X.go( "asdf" ) Traceback (innermost last): File "<console>", line 1, in ? TypeError: unbound method go() must be called with instance as first argument >>> The 'self' parameter is not a keyword - it is a convention. Methods on class X require an X instance: >>> X.go( X() ) called: <__main__.X instance at 5991085> >>> What you can do is cheat in one of two ways: class XGo: """Callable object to act as a static method""" def __call__( self, id ): print "called XGo(%s)" % id class XStatics: def go( self, id ): """Use the bound method as a static method""" print "called XStatics.go(%s)" % id # ... and other "static" methods class X: go = XGo() __xstatics = XStatics() go2=__xstatics.go # ... and other static methods X.go( "asdf" ) X.go2( "zxcv") Then executing that from emacs: Jython 2.1a1 on java1.3.0 (JIT: null) Type "copyright", "credits" or "license" for more information. ## working on region in file d:/TEMP/python-289AX1... >>> called XGo(asdf) called XStatics.go(zxcv) >>> kb |