[Tutor] Classes, methods and self

Lloyd Kvam pythontutor@venix.com
Fri Aug 1 12:59:01 2003


http://www.amk.ca/python/writing/warts.html
Python Warts

I pasted the Andrew Kuchling's comments about using self below.  I believe
that Python's approach of explicit object references is preferable to
implicit object references, but neither is perfect.  Is there a third
alternative???

***********
Explicit self in Methods

It's been suggested that the requirement to use self. to access attributes within class methods is tolerable but awkward, and the implied this from C++ and Java would be better. Perhaps this is a matter of preference; my Java code is instantly 
recognizable by the constant explicit use of this.attribute all over the place. Many Java or C++ coding standards dictate that object attributes should have a special prefix (e.g. m_) to distinguish them from locals; perhaps those who forget self are 
doomed to reinvent it.

If self. is too much typing for you, you can use a shorter variable name instead of self:

def method (s, arg1, arg2=None):
     s.attr1 = arg1
     if arg2 is not None:
          s.other_meth(arg2)

Using s instead of self doesn't follow the normal Python coding conventions, but few people will have difficulty adapting to the change.

Justin Heath wrote:

> I am going through some various class documentation (Learning to Program 
> and Learning Python) and I cannot seem to understand why self is needed 
> in a method declaration. I "believe" that I understand what self does 
> (i.e. connects itself to the current object instance). However, what I 
> do not understand is why you have to explicitly declare self in the 
> argument list of a method. I hope that was clear. Can anyone clarify 
> this for me?
> 
> Thanks again,
> Justin
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582