Python嵌套函数变量上下文疑问:micrograd中_backward闭包的变量访问
关于micrograd中嵌套函数闭包的疑问
以下是相关代码片段:
class Value: """ stores a single scalar value and its gradient """ def __init__(self, data, _children=(), _op=''): self.data = data self.grad = 0 # internal variables used for autograd graph construction self._backward = lambda: None self._prev = set(_children) self._op = _op # the op that produced this node, for graphviz / debugging / etc def __add__(self, other): other = other if isinstance(other, Value) else Value(other) out = Value(self.data + other.data, (self, other), '+') def _backward(): self.grad += out.grad other.grad += out.grad out._backward = _backward return out
在__add__方法内部定义的_backward函数被绑定到新创建的Value对象out的_backward属性上,该函数引用了self和other变量。清楚定义时这两个变量的来源,但疑惑当out._backward被调用时,它为何能获取到self和other对象?
这是**闭包(Closure)**的特性在起作用。
当你在__add__方法内部定义_backward函数时,这个函数会捕获并保留定义它时所在的词法环境——也就是当时的self和other变量引用。即使__add__方法执行完毕退出,_backward函数依然能访问这些变量,因为闭包会把这些变量的引用留存下来,直到_backward本身被销毁。
换句话说,_backward函数在定义时就已经“记住”了self和other这两个对象的引用,后续调用它时,自然能直接操作这两个对象的grad属性。
内容的提问来源于stack exchange,提问作者Tarique
相关产品推荐
相关产品推荐

