Home > Software design >  The best way to use self in function
The best way to use self in function

Time:09-29

For example I have the following code:

class printconct:
    def __init__(self, a):
        self.a = a
    
    def run1(self):
        print(self.a)
        
    def run2(self):
        a = self.a
        print(a)

a = printconct("a")
a.run1()
a.run2()

Is there any different between run1 and run2 function? I know that both of them have the same result, may question is there any cases that it's better to use run1 and other for run2. For example if I'm using variable a many time it's better to use run2 etc.

CodePudding user response:

Well, try it yourself

class printconct:
    def __init__(self, a):
        self.a=a

    def run1(self):
        s=0
        for i in range(10000000):
            s =self.a self.a self.a self.a self.a
        return s

    def run2(self):
        s=0
        a=self.a
        for i in range(10000000):
            s =a a a a a
        return s

On my computer, there is a factor 2 in computation time (run2 is twice as fast).

Note that

  1. I had to introduce a for loop so that timing measurement, or method call is negligible in the total timing
  2. Use several times the variable inside the for loop, so that the for loop itself stay negligible

So, yes, using a is twice as fast as using self.a.

But, also, I had to work to get into situation where it really matters.

The call for the method itself takes more time. Plus, obviously, if your just a=self.a and then use a only once, well, you gain nothing (and loose even some) because you used self.a (doing a=self.a) to spare nly one usage of self.a.

CodePudding user response:

def run1(self):
    print(self.a)
    
def run2(self):
    a = self.a
    print(a)

just noting that python is pass-by-object-reference. For run1, you would be referencing an existing variable. No additional memory is allocated. For run2, if self.a is an immutable object:

 a = self.a 

will allocate more memory for local variable 'a' and create a copy of self.a.

  • Related