ysBach
ysBach

Reputation: 361

Should I use self.variable for all class methods?

I wanted to search whether there's similar question but I don't even know what keywords to search.

I want to make a class something like this (simplified a lot for this post):

class MyClass:
    def __init__(self, a, b=None):
        if b is None:
            b = 0
        self.a = a
        self.b = b

    def do_calc(self, const=None):
        if const is None:
            const = 1
        abc = self.a*self.b*self.const
        self.const = const
        self.abc = abc
        self.result = self.abc**2 + self.b*self.const**2 + 2*self.abc + self.const

My question is whether I can shorten the last line in the do_calc part to

        self.result = abc**2 + self.b*const**2 + 2*abc + const

In my real code, the last line gets too long if I use self. in front of all the variables, so I wanted to shorten them without losing readability. Of course the code should work, but I wonder if there's any potential problem by doing this way. I had this feeling that it's better to use self. all the time but I find I have no concrete reason for that so far.

Upvotes: 0

Views: 66

Answers (1)

chepner
chepner

Reputation: 532538

Your definition of do_calc is unnecessarily long, as there is no need for abc or const to be stored as instance attributes. You can, however, save self.a and self.b as temporary local variables to shorten the calculation.

def do_calc(self, const=1):  # 1 is immutable, so it's safe to use as a default
    a = self.a  # Optional, you can refer directly to self.a below
    b = self.b  # Optional, you can refer directly to self.b below
    abc = a * b * const
    self.result =  abc**2 + b*const**2 + 2*abc + const

Another issue is whether do_calc should cache this result in the instance itself, or simply return the value calculated.

def do_calc(self, const=1):
    a = self.a
    b = self.b
    abc = a * b * const
    return abc**2 + b*const**2 + 2*abc + const

Upvotes: 1

Related Questions