Too many 'self' in python.That's a big flaw in this language.

A.T.Hofkamp hat at se-162.se.wtb.tue.nl
Wed Jun 27 10:37:50 EDT 2007


On 2007-06-27, hide1713 at gmail.com <hide1713 at gmail.com> wrote:
> HI
>     I'm currently using Python. I find that a instance variable must
> confined with self,
> for example:
> class a:
>     def __init__(self):
>         self.aa=10
>     def bb(self):
>         print self.aa # See .if in c++,I could use aa to change that
> variable

c++ is a much more static language (for example, you cannot create new fields
in your class at run time), so it can decide in advance what you mean.

In other words, it is a cost you pay for the increased flexibility. You may not
be using that flexibility, but it is there, and people use it.

> That's a big inconvenience in coding ,especially when you have lot of
> variable

I have switched from c++ to Python several years ago, and was surprised about
having to explicitly write 'self' each time. However, I never considered it "a
big inconvenience".
As years went by I have come to like the explicit notation in Python.


> Or any way to make programmer's life easier?

Others have already pointed out that leaving out 'self' is more bad than good.
I think they are right. In the past I also thought that Python was badly
designed, and until now, in the end it appeared that I was always in error.
[off-topic:
 I think that again now with the default implementation of the object.__eq__ and
  object.__hash__ methods. I believe these methods should not exist until the
  programmer explicitly defines them with a suitable notion of equivalence.

  Anybody have a good argument against that? :-)
]


Another suggestion may be to look at your code again, and check whether all
self's are really needed. In other words, can you improve your code by reducing
use of instance variables?
In Python, The "a=b" statement is extremely cheap, because you don't copy data.
Exploit that feature.

An alternative may be to copy a self variable into a local variable one and use
the local variable in the method. Another option may be to collect results in a
local variable first and then assign it to a self.X variable.

If you really have a lot of variables, are you sure that they should all be
seperate (flat) variables in one class, ie would it be possible to merge some
of them together in another object and have more structure in the variables?
(classes are much cheaper in Python than in c++ w.r.t. amount of code)


Sincerely,
Albert



More information about the Python-list mailing list