It might be a silly question, but I'm new to Python. I would like to understand how the following segment of code is possible.
class test:
def main_method(self):
variable = 10;
def sub_method(input):
return input * variable
self.result = sub_method
obj = test()
obj.main_method()
print(obj.result(4))
Output:
40
My question:
When I execute obj.result(4), how does self.result, being an instance variable that stores sub_method, has access to the scope of main_method and the value of variable without executing main_method again?
Thank you very much.
sub_methodkeeps the state of the free variables along with it. Python supports closuresmain_methodjust a method, not a class method.