Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid using 'self' so much [duplicate]

Tags:

python

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?

like image 573
pap42 Avatar asked Feb 16 '14 18:02

pap42


2 Answers

For messy parts I'd use Python modules and "module-level variables" instead of classes.

like image 98
iljau Avatar answered Oct 16 '22 12:10

iljau


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.

like image 22
Bas Swinckels Avatar answered Oct 16 '22 12:10

Bas Swinckels