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)
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 witha.__dict__['x']
, thentype(a).__dict__['x']
, and continuing through the base classes oftype(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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With