self
Eric Brunel
eric.brunel at pragmadev.com
Tue Jun 4 14:38:22 EDT 2002
Vojin Jovanovic wrote:
> I have been working on a project trying to implement some advanced
> functionality. Now, one thing that has been a constraint for me is the
> concept of self. Why is it that within a class one has to use self. (or
> "any word". ) to refer to instance variables? Would it not be more logical
> to just use the name of the variable like it is for example in C++?
This is *not* a variable, this is an attribute. Hence the "self.". I always
found the C++/Java convention particularly disturbing. With this
convention, there's no obvious means to tell a local variable from an
object's attribute:
public class C {
public int a;
public void m() {
int b;
a = 0; // What's the difference
b = 0; // between these 2 lines?
}
}
The notation is exactly the same for two quite different things:
- "a = 0;" means "set the value of attribute a of method's receiver to 0",
setting that will still exist after the method's end
- "b = 0" means "set the value of the variable b, local to method m, to the
value 0", setting that will be discarded after the method's end
Not using any prefix in front of attribute names in methods is IMHO a
dangerous shortcut, and a confusing one... I really prefer Python's
notation, which is indeed a bit "heavier", but far less confusing. You'll
certainly find your code far more readable in a few months than it would be
in C++ or Java.
--
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
More information about the Python-list
mailing list