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

Alan Gauld alan.gauld at btinternet.com
Fri Jul 3 11:32:52 CEST 2015


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

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

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list