Search code examples
pythonmethodspython-3.xinternals

Why are references to instance methods stored in each instance object rather than in the class object?


From what I understand, each instance of a class stores references to the instance's methods.

I thought, in concept, all instances of a class have the same instance methods. If so, both memory savings and logical clarity seem to suggest that instance methods should be stored in the class object rather than the instance object (with the instance object looking them up through the class object; of course, each instance has a reference to its class). Why is this not done?

A secondary question. Why are instance methods not accessible in a way similar to instance attributes, i.e., through __dict__, or through some other system attribute? Is there any way to look at (and perhaps change) the names and the references to instance methods?

EDIT:

Oops, sorry. I was totally wrong. I saw the following Python 2 code, and incorrectly concluded from it that instance methods are stored in the instances. I am not sure what it does, since I don't use Python 2, and new is gone from Python 3.

import new
class X(object):
  def f(self):
    print 'f'
a = X()
b = X()
def g(self):
  print 'g'
# I thought this modified instance method just in a, not in b
X.f = new.instancemethod(g, a, X)

Solution

  • From what I understand, each instance of a class stores references to the instance's methods.

    I don't know where you got this from, but it's wrong. They don't.

    Why are instance methods not accessible in a way similar to instance attributes, i.e., through __dict__, or through some other system attribute?

    Well, because they are not stored on the instance.

    Is there any way to look at (and perhaps change) the names and the references to instance methods?

    Since these references don't exist, you cannot change them. You can of course create any attribute you want by normal assignments, but note that functions stored on the instance are not treated like ordinary methods -- the mechanism that implicitly passes the self parameter does not apply for them.