Why self?

Brian Quinlan brian at sweetapp.com
Mon Jul 8 17:56:57 EDT 2002


Robb Schecter wrote:
> > (1) All self variables have to be initialized in __init__.  That's
just
> > good practice anyway.  They are labeled with self in __init__
otherwise
> > they are local.
> >
> > (2) There can be no name conflicts between local and self variables.
> > Also good practice within an object.
> >
> 
> Good ideas.  Or just do nothing: make self optional as in Java, and
the
>   innermost scope is searched first if no self is given.  I've done
> years of Java programming, and have never had issues with instance vs.
> local variables.  It just really doesn't happen in practice because of
> the differences in naming and usage of variables.

In doesn't happen in practice because Java is much less dynamic than
Python. The complete list of instance variables is known at compile
time. The complete list of instance variables is not generally
discoverable in Python (not even at runtime). Since variable
declarations are not used, searching the innermost scope wouldn't work.
Imagine this:

	def foo():
		x = 5

How would you know if that is an instance variable or a local?
 
> How does Ruby handle this?

Instance variables are prefixed with '@'.

> I think that any of these ideas are good.

Yech.

Cheers,
Brian






More information about the Python-list mailing list