After I ran "a.method",why the sys.getrefcount(a) returned 3? there was no new variable referred the object
class A(object):
def method(): pass
import sys
a=A()
sys.getrefcount(a) # returns 2
a.method
<bound method A.method of <__main__.A object at 0x7f1e73059b50>>
sys.getrefcount(a) # returns 3
In the python interactive shell, the result of the last command is stored in a special varialbe named _
. Naturally, this variable holds a reference to that result.
In your case, the result is a method object, which holds a ref to its "self", i.e. the variable a
. In other words, in the case you describe, the extra ref is indirect. The result (<bound method A.method of <__main__.A object at 0x7f1e73059b50>>
) which is kept alive due to variable _
, holds a reference to <__main__.A object at 0x7f1e73059b50>
.