Vineeth Bhaskara Vineeth Bhaskara - 1 month ago 8
Python Question

Passing a class's "self" to a function outside it such that the class's variables are accessible and modifiable?

Can I pass the

self
instance variable of the class from within the class to some helper function outside the class? For example, will the following work when an object of SomeClass is initialized? Isn't there any type casting required? Is this coding style reliable? Is there any possibility of this feature being dropped off in future releases of Python 2.x?

class SomeClass():
var1 = 7
def __init__(self):
some_func(self) # passing self instead of self.var1

def some_func(instance):
instance.var1 += 1

x = SomeClass()
print x.var1


I have
some_func
as a common helper function across many classes that undergo the same transformation, and the
var1
in my current application is a huge dataFrame which I cannot afford to pass a copy of it to the function due to memory constraints. Do you have any suggestions?

am2 am2
Answer

The easiest way would have been to try it out :) yes, it works, as you expect

class SomeClass():
    var1 = 7
    def __init__(self):
        some_func(self) # passing self instead of self.var1

def some_func(instance):
    instance.var1 += 1

x = SomeClass()
print x.var1

But in most cases it would be better to make some_func to a member of SomeClass

Comments