Do I always have to write "self." ?

Cedric Adjih adjih at
Fri Apr 28 16:12:01 CEST 2000

Louis M. Pecora <pecora at> wrote:
> In article <slrn8ghc6t.f01.scarblac-spamtrap at>,
> Remco Gerlich <scarblac-spamtrap at> wrote:

>> No. However, this seems to make code *more* readable. In fact, many C++
>> programmers use 'this.x' for all their instance variables, to be able to
>> see at a glance which are just local variables of the function and which are
>> instance variables. It's just more work to write, but that doesn't matter
>> much.

> I understand the potential for readability, but I do a lot of
> mathematical programming so the expressions can get pretty cluttered
> with variables and operators.  More self's only makes it worse for me. 
> Maybe that's my problem, but then that's my complaint.

Alternatively you could use 1-liners, if it is justified

class Polynom2:
	def __init__(self,a,b,c):
	def delta(self):
		return self.b*self.b-4*self.a*self.c

Often, 1-liners will remove the need for one comment.

>> Python needs it to know which vars are instance variables, and which are
>> local variables.

> I'm sure some way of declaring variables 'local' could be done in the
> class defintion, but I doubt Guido would do that now.

>> Funny how people say that every aspect of Python they don't like make the
>> language less "clean". It is extremely consistent though.

> Funny, I guess.  Harder to read for me.

>> You *can* use another word for 'self' though, 's' or 'me' or something. But
>> it makes your code harder to read, of course...

> You mean by doing something like

> s=self
> at the beginning of each class method?

The name 'self' is just a convention.
But since some parsing software will rely on it, "s=self"
might be wiser.

class Polynom2:
	def delta(s): return s.b*s.b-4*s.a*s.c


class Polynom2:
	def delta(self):
		return s*b*s.b-4*s.a*s.c

or the other suggestions for read-only attributes:

class Polynom2:
        def delta(self):
                return b*b-4*a*c

-- Cedric

More information about the Python-list mailing list