Here I defined a class with custom ___mul__ operator.
Inside the __mul__ operator I define a _backward function that use an argument to that function (other variable ).
How does python keep track of the other variable when I call the _backward function on out.
Does it internally keep track of the scope in which the function is defined?
class Value:
def __init__(self, data):
self.data = data
self.__rmul__ = self.__mul__
def __mul__(self, other):
out = Value(self.data*other.data)
def _backward():
print('Backward of ', self.data, other.data)
out._backward = _backward
return out
def __rmul__(self, other):
self.__mul__(self, other)
a = Value(10)
b = Value(5)
o = a*b
o._backward()
Output:
Backward of 10 5