Dominik Dominik - 3 months ago 10
Python Question

Local binding of "self" to another variable in instance methods acceptable?

Is it acceptable according to the standards of best practice to locally bind self in a instance method to another variable? It comes in handy, especially when testing the method. I would also like to like know whether this approach is more efficient if instance attributes are retrieve within loops. Here is an example

class C:
def __init__(self):
self.a = "some attribute"

def some_function(self):
c = self
for _ in range(10):
print(c.a)

Jim Jim
Answer

This generally offers no benefits. The only up-side of doing this (a bit differently) is if you want to eliminate the attribute look-up:

def some_function(self):
    c = self.a   # note, we assign 'a'
    for _ in range(10):
        print(c)    

which will reduce execution speed on a minuscule degree. Other than that you really get no benefit of renaming self like that.