0

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
mrid
  • 5,782
  • 5
  • 28
  • 71
Jay
  • 113
  • 8
  • please learn how to create a How to create a Minimal, Complete, and Verifiable example before posting a question( https://stackoverflow.com/help/mcve ) – mrid Sep 20 '17 at 10:01
  • Are you using IPython or some other IDE? – cs95 Sep 20 '17 at 10:01

1 Answers1

2

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>.

shx2
  • 61,779
  • 13
  • 130
  • 153
  • 1
    The fun thing is that when you call `sys.getrefcount(a)` _again_, then it returns 2 because of what this answer describes (`_` is the integer `3` after the first `sys.getrefcount(a)`). – eepp Sep 20 '17 at 20:50