I want to define a function, call it test_controller()
, and I want to pass this function to a constructor: my_thing = TestClass(test_controller)
. This function needs to be able to modify its class's data objects. I've heard of the nonlocal
keyword for Python 3, but I'm running Python 2.7. Is it possible? How do I do this? Here's what I have tried already.
class TestClass(object):
def __init__(self, ctrl_func):
self.a = 4
self.ctrl_func = ctrl_func
def do_stuff(self):
self.ctrl_func()
def test_controller():
global a
a = 20
my_thing = TestClass(test_controller)
print my_thing.a #this prints 4
my_thing.ctrl_func()
print my_thing.a #this prints 4 but I want it to print 20