Recursive method

Greg Ewing greg.ewing at compaq.com
Wed Jul 14 16:58:08 EDT 1999


Ralph Gauges wrote:
> 
> class Test:
>         def TestMethod(self):
>                 print "ABC"
> 
>         TestMethod(self)        # <- this doesn't work, because
> there is no 'self'
>         self.TestMethod()       # <- this doesn't work, because
> there is no 'self'

The reason there's no 'self' here is simply
that the code is not being executed in an 
environment where a name 'self' is defined.

Code which is inside a class definition but
not inside a method is executed when the class
is defined. At that time there isn't any instance
of the class that could be called 'self', so
it doesn't make sense to want to have 'self'
defined then.

This applies to both Python and JPython,
by the way. The code you wrote wouldn't work
in Python either.

If you want initialisation code which is only
executed once, the best place to put it is at
the module level, outside of any class definition.
Then you can make recursive calls, etc. without
any problem (as long as you don't nest function
definitions).

On the other hand, if you want initialisation code
executed for each instance (e.g. if the class
corresponds to a window, and you want a new
window for each instance of the class) then
the code has to go in the __init__ method, or
other methods that it calls. Again, methods can
call themselves or each other without problem.

Keep in mind that code in the class body is only
executed *once*, not every time an instance is
created.

Hope that helps,
Greg




More information about the Python-list mailing list