6

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)

4 Answers 4

7

Attribute lookup on objects in Python is non-trivial. But instance methods are certainly not stored on the instance object!

The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, a.x has a lookup chain starting with a.__dict__['x'], then type(a).__dict__['x'], and continuing through the base classes of type(a) excluding metaclasses.

(docs)

Note that it is possible to store a function on an instance. But that's not an instance method! When the interpreter looks up an attribute and finds that it is (a) a function and (b) on the class object, it automatically wraps it in a bound method object which passes self.


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

Well, you can certainly modify the class object after defining it. But I assume what you mean is "can you make the x method of a particular instance do something different?"

This being Python, the answer is "yes": just define a.x to be some new function. Then you will get that function back before looking on the class.

This may cause you a lot of confusion when you're trying to understand the code, though!

3
  • 2
    Overwriting a method, even on a per-instance basis, does not necessarily break the LSP, or any other such contract. The method you supply instead might just as well do the same thing from the caller's POV. Otherwise, even polymorphism and overriding methods in subclasses would be out of question. I'd give a tenative -1 but I can't check back for edits or justifications within the next hour (i.e. I couldn't revert a downvote).
    – user395760
    Mar 19, 2012 at 16:45
  • @delnan you are correct. I meant a more handwavey contract than Liskov; that function lookups on instances should give instance methods. I'll rewrite.
    – Katriel
    Mar 19, 2012 at 16:49
  • Understood. So instance methods are stored in the class' __dict__, which is precisely where I expected them to be. Sorry for the dumb question.
    – max
    Mar 19, 2012 at 17:06
6

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.

5
  • 2
    your answer communicates that the asker is wrong, but not why.
    – MK.
    Mar 19, 2012 at 16:45
  • @MK: Could you expand on this? The reason the OP is wrong is that methods are not stored on the instance. You could get philosophical about language design here, but basically the OP covered all this in the question -- waste of memory etc. I think this is an ill-reasoned downvote. Mar 19, 2012 at 16:50
  • Ahh, sorry... just edited the question to explain the source of my confusion.
    – max
    Mar 19, 2012 at 17:04
  • Well, I'll take away the downvote, but I think you need a link of some sort to support your claim (like the one I got downvoted for below)
    – MK.
    Mar 19, 2012 at 17:21
  • @MK.: Thanks. The mechanism behind attribute look-up is rather complex, and there isn't a single good link explaining that this does not happen, at least I'm not aware of one. Mar 19, 2012 at 17:31
1

Incorrect. Instances do not store references to each method.

For example:

class Foo():
    def bar(self):
        print 'bar'

f = Foo()
def alternate_bar(self):
    print 'alternate bar'

f.bar()    
Foo.bar = alternate_bar # modifies the class!
f.bar()

prints

bar
alternate bar

This is also why you provide a self to each method you define in a class. Without a reference to self, the method has no idea which instance it is working on.

1

Another example

class Point:
    def __init__(self, xcoord, ycoord):
        self.x = xcoord
        self.y = ycoord
    def draw(self):
        print self.x, " ", self.y

p = Point(205.12, 305.21)

#draw the coordinates of the point instance

p.draw()

# now define a new point drawing function vdraw()

def vdraw(q):
    print "[",q.x,",",q.y,"]"

#p.draw()

#now reassign the draw() method to vdraw()

Point.draw = vdraw

# now print the coordinates of the point instance 

print p.x
print p.y

#now draw the coordinates of the point instance
p.draw()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.