Apr-12-2023, 03:25 PM
(This post was last modified: Jun-15-2023, 03:38 PM by deanhystad.)
A lambda expression like "lambda: self.b" creates a closure. The object self is referenced by the closure. You can see that here:
class Exp: def __init__(self): self.a = 1 self.b = lambda: self.a def __str__(self): return f"a: {self.a}, b:{self.b()}" obj = Exp() print(obj) obj.a = 2 print(obj)
a: 1, b:1 a: 2, b:2How does the lambda expression know the value of obj.a has changed to 2? It knows because it created a closure that not only knows what code to execute (return self.a), but contains a reference to the object self. When you reassign obj = None this does not remove the reference in the lambda expression. To do that:
obj = Exp() obj.b = None obj = NoneNow the reference count goes to zero and the object is deleted.