Do I always have to write "self." ?

Louis M. Pecora pecora at anvil.nrl.navy.mil
Fri Apr 28 07:51:34 EDT 2000


In article <8eacdf$nnm$1 at newshost.accu.uu.nl>, Martijn Faassen
<m.faassen at vet.uu.nl> wrote:

> There's a way, but stuff can also become more cluttered. In some
> cases it'll also be a bit faster, as local variable access is
> faster than access through self. In lots of other cases it can be slower.
> I'll demonstrate:
> 
> class Foo:
>     def __init__(self):
>         self.data = []
>         self.more = 10
>         self.interesting = "foo"
>         
>     def involved_method(self, something):
>         data, more, interesting = self.data, self.more, self.interesting
> 
>         if more > 15:
>             data.append(something)
>             data.append(interesting)
> 
> But note this!
> 
>     def uhoh_method(self):
>         data, more, interesting = self.data, self.more, self.interesting
>         # this changes self.data, neat
>         data.append('foo') 
>         # this won't change self.more!
>         more = more + 1
>         # and this won't change self.interesting
>         interesting = interesting[10:]
> 
> So, beware when you want to change attributes that refer to immutable
> objects. You do have to use self in that case. I think that you'll
> find that eventually you'll get used to 'self', and you may even
> be grateful for its presence. At least you can see instantly where
> your variable are coming from. The local variable trick, used in moderation,
> can help some as well.

Martijn,

Thanks for the very nice tutorial.  Your example brings up some typical
stumbling blocks for us beginners.  Namely, references to mutable and
immutable objects.

In the above I would describe things as follows (am I right or wrong?):

(1) data and self.data point to the same object, a list, so when a
method is called it is the method that works on that instance of a list
and either data or self.data will append 'foo' to the same list object.

(2) when you do more=more+1 an new object (the more+1 value) is created
and more then points to it and no longer to the old value of self.more. 
The latter still exists and points to the original 10 object.

(3) Similar story here for interesting where a new object
interesting[10:] is created and interesting is "switched" to point to
it.  self.interesting still points tohe "foo" object.

I hope I got that right, because they have tripped me up a few times.

Thanks, again.



More information about the Python-list mailing list