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

Alan Gauld alan.gauld at btinternet.com
Thu Jul 2 23:18:15 CEST 2015


On 02/07/15 20:30, 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?

As soon as you mention memory space in relation to how something
works in Python you know you are barking up the wrong tree.
Memory space is a concept that only applies at the
implementation level in Python, never in the concepts.

Python objects (including classes, which are just another object)
are not necessarily constrained to a single memory space, Classes
are conglomerations of other objects (data and functions) and
linked to other classes (via inheritance). This is not like C++
(or even Java).

The method definitions inside a class define method objects
that live in their own conceptual space as values in the dictionary that 
defines the class structure. Two methods of the same class
could live in wildly different memory locations or they could all be 
part of the same memory area. That's an implementation detail and likely 
to be very different in CPython, Jython and IronPython etc..

So the question should be whether Python objects access the references 
to those methods by linking through the class object or whether they
get copies of the references internally.

I think Danny's answer covers that aspect.

But remember that questions of where Python objects live
in memory are nearly always the wrong question to ask.

Finally, I'm guessing that when you said a "class method" you
actually meant a "method in a class", ie an instance method? You
did not mean an actual class method as defined using the
@classmethod decorator?

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