How not to use the ego so much

I am writing a program to simulate a small physical system and get more annoyed when I write things like this:

K = 0.5 * self.m * self.v**2

In the above case, the equation is short and pretty straightforward, but I have situations in which there is so much self that it all looks like a mess. I know that python always requires self refer to class members, but is there a way to make the code not look like self mosaic?

EDIT . I usually do things like:

var = self.var

and keep using var instead of self.var . Later I:

self.var = var

but it seems really stupid. What will be the pythonic way to solve this problem?

+8
python
source share
3 answers

For the messy parts, I would use Python modules and "module level variables" instead of classes .

+2
source share

If all you want to do is save some keystrokes, you can always rename self to s :

 class MyClass(object): def kinetic_energy(s): # use s instead of self for brevity return 0.5 * sm * sv**2 

This saves 3 characters per use of self . This is contrary to the standard agreement, but nothing prevents you from doing this. I would advise doing this in general code, but it can be justified if it makes some very long formulas more readable. Mention the unusual choice in the comment if someone else should read your code when you are long gone.

+2
source share

I assume that you can use black magic in Python and come up with a context manager that takes the object and puts its entire attribute in the locals() context and assigns it back to the object in the __exit__ function.

Found https://code.google.com/p/ouspg/wiki/AnonymousBlocksInPython that might help.

0
source share

All Articles