newbie: self.member syntax seems /really/ annoying

Bruno Desthuilliers bruno.42.desthuilliers at
Wed Sep 12 12:36:04 CEST 2007

Charles Fox a écrit :
> I've just started playing around with Python, as a possible
> replacement for a mix of C++, Matlab and Lisp.  The language looks
> lovely and clean with one huge exception:  I do a lot of numerical
> modeling, so I deal with objects (like neurons) described
> mathematically in papers, by equations like
>     a_dot = -k(a-u)
> In other languages, this translates nicely into code, but as far as I
> can tell, Python needs the ugly:
>     self.a_dot = -self.k(self.a-self.u)

"ugliness" is a very subjective notion. As far as I'm concerned, I hate 
the "m_myMember" C++ convention, and have always used the 'this' (or 
whatever it's named) pointer/reference/pseudo-reference/whatever in 
languages where it's implicit - because I don't like such an important 
thing to be implicit.

  self.a_dot = - self.k(self.a - self.u)

> For large equations this is going to make my code seriously unreadable

Ok, but this is another problem.

> to the point of needing to switch back to Matlab -- and it seems to go
> against everything else about python's simplicity and elegance.  Am I
> missing something? 


> Is there something like a 'with' command that lets
> me set the scope, like
>     with self:
>       .a_dot = -.k(.a-.u)

Nope. There's a 'with' statement, but it has nothing to do with this.

The obvious solution to your problem is to make local references to the 
needed attributes at the start of your method, ie:

def some_calc(self, whatever):
   k = self.k # yes, it works for methods too
   a = self.a
   u = self.u

   self.a_dot = -k(a-u)

> It's premature to make language suggestions as I am new to the
> language, but I would have though that making a 'with self' explicit
> in all methods would have been neat, so I could just write
>       .a_dot = -.k(.a-.u)
> which would still avoid confusion with local function variables, since
> '.a' is different from 'a'.
> Please help if I am missing something -- this looks like a great
> language but I am going to mad trying to read numerical code full of
> 'self.'s breaking up the equations.

The mandatory 'self' (FWIW, you can name it as you want, 'self' is just 
a convention) has long been the topic of lot of debates. While I do 
understand your motivations, there are actually good reasons for this 
design choice, but understanding these reasons requires some knowledge 
of Python's object model internals. As far as I'm concerned, I'm quite 
happy with the current design, but I don't do much maths !-)

More information about the Python-list mailing list