Re: [Jython-users] Why is self used so much
by hamish other posts by this author
Feb 27 2002 6:27PM messages near this date
Re: [Jython-users] Why is self used so much
|
[Jython-users] Example of Java class reloading
Sorry Martin - I'll post properly this time :-)
Martin wrote:
Hi,Im new to jython and python but have been programming in java for
a while. I was just wondering why it seems that every variable used has
to
have self prefixed to it. A basic applet example of mine is below.
This wouldnt compile/run until self was placed before each variable and
between
the brackets of init.I'd just like to know why this is needed or if im
doing something wrong.from javax.swing import *
from java.awt import *
class Button1(JApplet):
b1 = JButton("Button 1")
b2 = JButton("Butotn 2")
def init(self):
self.cp = self.getContentPane()
self.cp.setLayout(FlowLayout())
self.cp.add(self.b1)
'self'' is the naming convention for the instance reference and is
effectively the equivalent of 'this' in Java. However it isn't a
keyword in Jython (or CPython) and must be the first parameter declared
in all instance methods. On invocation, 'self' is
replaced by the reference to the object instance, i.e.
class MyClass:
def __init__(self):
# blah blah
def doit(self):
# blah blah
myInst = MyClass()
myInst.doit()
where the self of doit() refers to myInst. It's just that (J/C)Python
requires you to be explicit about how the object
reference gets to the bit of code in question. This is finessed by
languages like Java and C++ but essentially the same
thing happens in "real code". 'this' is just an implicit parameter for
the function in question.
I haven't quite got my own head around the difference between class and
intance methods in Python and I certainly didn't
like this construct at first. But see the way Perl does it for objects
and maybe you'll bless Jython a little more :-)
You are of course free to use 'this' or any other non-conflicting name
instead of 'self' - it's just that 'self' is the de facto
standard.
BTW : the constructor of a class is the method def __init__( self ).
Not sure if that was your intention in the code you
quoted.
Regards
Hamish
PS what I forgot to mention is the fact that you do need to distinguish
between instance variables and local variables inside a method.
self.varname referes to an instance variable
leaving off the self. prefix just leaves you with a variable varname
which is scoped locally to the function.
_______________________________________________
Jython-users mailing list
Jython-users@[...].net
https://lists.sourceforge.net/lists/listinfo/jython-users
Thread:
Martin
Doug Landauer
hamish
|