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

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Jul 3 16:47:04 CEST 2015


On 3 July 2015 at 02:17, Steven D'Aprano <steve at pearwood.info> 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.
>
> When you define a class in you define methods and other attributes in
> the class namespace:
>
> class C:
>     attr = 23
>     def method(self, arg):
>         pass
>
[snip]
>
> When you call a method, c.method(), Python does a name look-up.
> Simplified, it looks in c.__dict__, then C.__dict__, then the __dict__s
> of each of C's parents (if any).

To expand on this slightly. The expression c.method() is calculated as
(c.method)(). So the expression c.method must be evaulated first. To
evaluate this the name lookup occurs and a bound method object is
created. The bound method object wraps together the instance with the
method that was found during lookup. Having evaluated the expression
c.method the resulting bound method is then called to complete the
evaluation of the expression c.method(). Subsequently replacing the
method in the class does not affect the bound method since the lookup
has already occurred:

>>> class A:
...     def foo(self):
...         print('Original foo')
...
>>> a = A()
>>> afoo = a.foo
>>> A.foo = lambda self: print('New foo')
>>> afoo
<bound method A.foo of <__main__.A object at 0x7fefd773cc50>>
>>> afoo()
Original foo
>>> a.foo()
New foo

--
Oscar


More information about the Tutor mailing list