Holding reference to out of scope object's method
<pre><code>class Foo:
    def __init__(self, _label):
        self.label = _label
    def display(self):
        print(str(self.label))
    def get_display(self):
        return self.display

display_test = Foo(1).get_display()
display_test()
def inner_scope():
    global display_test
    display_test = Foo(2).get_display()
inner_scope()
display_test()
</code></pre>

<p>In Python 2.7, the above block prints 1 followed by 2, which isn't terribly surprising. What I'm curious about, though, is what happens to the objects generated by <code>Foo(1)</code> and <code>Foo(2)</code> -- it appears as though they have not been garbage collected as of the time <code>display_test</code> gets invoked, but does that mean <code>display_test</code> has a reference to <code>Foo(2)</code>, preventing it from being garbage collected at all? Am I just getting lucky that the objects aren't garbage collected before I invoke <code>display_test</code>? Does this differ in <code>3.x</code>?</p>

<p>In Python 2, <code>display_test</code> holds a reference to an <code>instancemethod</code> object, one of whose attributes is <code>im_self</code>, the instance the method is bound to.</p>

<p>In Python 3, <code>display_test</code> holds a reference to a <code>method</code> object, one of whose attributes is <code>__self__</code> (the Python 3 equivalent of <code>im_self</code>).</p>

python python-2.7 python-3.x garbage-collection