I am writing a program to simulate a small physical system and have become more and more annoyed as I write things like this:
K = 0.5 * self.m * self.v**2
In the case above, the equation is short and pretty understandable, but I have situations in which there is so much self
that the whole thing ends up looking like a mess. I am aware that python always requires self
to refer to class members, but is there a way to to make the code not look like a mosaic of self
's?
EDIT: I usually do things such as:
var = self.var
and keep on using var
instead of self.var
. Later I do:
self.var = var
but this seems really stupid. What would be the pythonic way to solve this problem?
For messy parts I'd use Python modules and "module-level variables" instead of classes.
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 * s.m * s.v**2
This saves you 3 characters per use of self
. This goes against the standard convention, but nothing is stopping you from doing this. I would advice against doing this in general code, but it might be justified if it makes some very long formulas more readable. Do mention the unusual choice in a comment, in case anyone else has to read your code when you are long gone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With