Do I always have to write "self." ?

Martijn Faassen m.faassen at vet.uu.nl
Thu Apr 27 17:45:19 EDT 2000


Louis M. Pecora <pecora at anvil.nrl.navy.mil> wrote:
> I am two weeks plus into learning Python and have started on a first
> real project.  Amazing language.  BUT, now that I've gotten going with
> classes, I'm finding I hate seeing all those  "self."  prefixes on the
> class variables.  Python is generally very clean, but the classes I
> write use a lot of "per-instance" variables, hence seem to require
> self.  As a result the expressions can become cluttered and harder to
> read than C++ in this particular case -- imagine that!  Is there any
> relief here?  Any (simple) way around writing that self. every time?

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.

Regards,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list