[Tutor] Are the methods in a class copied or just linked to?

Steven D'Aprano steve at pearwood.info
Fri Jul 3 12:35:59 CEST 2015


On Fri, Jul 03, 2015 at 10:32:52AM +0100, Alan Gauld wrote:
> On 03/07/15 02:17, Steven D'Aprano wrote:
> >On Thu, Jul 02, 2015 at 12:30:23PM -0700, Jim Mooney Py3.4.3winXP wrote:
> >
> >>When an instance uses a class method, does it actually use the method that
> >>is in the class object's memory space, or is the method copied to the
> >>instance?
> >
> >The first. And it is not just an implementation detail, it is part of
> >Python's programming model.
> 
> Pythons implementation model does not dictate the memory space
> of the method. The method is in the class name space and referenced
> via the internal dict. But the actual memory space of the method
> object can be outside the memory space of the class. That's what
> I mean by implementation detail. You cannot for example do a
> memcopy of a class and expect to get a fully functioning
> independant clone of the class in the new memory space. Nor an you 
> reliably calculate a method's memory location by adding an offset
> to the class's location as you can in say C++ (a common way
> of gaining access to private methods in early C++ code).

Oh. Right, I agree with this. Classes, and instances, in Python can be 
spread over multiple chunks of heap memory. The specific details of 
where the various parts live in memory are not defined by the language, 
and will differ from implementation to implementation.

All you know is that methods (by default) will be found in the class 
__dict__, but not where the methods actually are located, of even where 
the class __dict__ will be located.


> >When you define a class in you define methods and other attributes in
> >the class namespace:
> 
> But this is true and the mechanism for looking up the method is defined 
> in the Python model and it goes via the class. But where the class 
> stores its methods is up to the implementation.

Methods are stored in the __dict__, but the location of the __dict__ is 
a mystery :-)


-- 
Steve


More information about the Tutor mailing list