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

Danny Yoo dyoo at hashcollision.org
Thu Jul 2 22:46:37 CEST 2015


On Thu, Jul 2, 2015 at 12:30 PM, Jim Mooney Py3.4.3winXP
<cybervigilante at gmail.com> 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?


Unsure.  How would it be observable?



[The following is not beginner material, and mostly
implementation-specific experimentation.  Skip if you are a beginner.]


We know that bound functions are more than code: they need to include
references to the otherwise free variables.  But I think the
underlying function code is shared.  It's not logically required, but
it makes engineering sense.  Otherwise, making bound functions would
be significantly more expensive than the obvious approach of sharing
the part that doesn't change.

As an example:

#########################################
>>> def f(name):
...    def g():
...       return name
...    return g
...
>>> d = f("danny")
>>> j = f("jim")
>>> d()
'danny'
>>> j()
'jim'
>>> id(d)
4407845544
>>> id(j)
4407847344
>>> d.__code__
<code object g at 0x106ba1cb0, file "<stdin>", line 2>
>>> j.__code__
<code object g at 0x106ba1cb0, file "<stdin>", line 2>
#########################################

Here, 'd' and 'j' may be different values, but they share the same
underlying __code__, the compiled code object that defines 'g'.



__code__ and __func__ are special variables used to access the
underlying function values.  They're described in:
https://docs.python.org/3/reference/datamodel.html

The following section in the reference are immediately relevant to
your question:

""""
When an instance method object is created by retrieving a user-defined
function object from a class via one of its instances, its __self__
attribute is the instance, and the method object is said to be bound.
The new method’s __func__ attribute is the original function object.

When a user-defined method object is created by retrieving another
method object from a class or instance, the behaviour is the same as
for a function object, except that the __func__ attribute of the new
instance is not the original method object but its __func__ attribute.

When an instance method object is created by retrieving a class method
object from a class or instance, its __self__ attribute is the class
itself, and its __func__ attribute is the function object underlying
the class method.
""""


>From my reading of this, the language reference is guaranteeing that
__func__ is shared.


More information about the Tutor mailing list