Skip to the solution
MediumDSA11 min read

What are bound and unbound methods in Python?

707 views

The problem

Question presented to candidate: "If I write obj.method without calling it, what do I actually get back? What is a bound method, what did 'unbound method' mean, and how does self get passed in?"

What a strong answer should cover:

  • A bound method is an object that pairs a function with an instance: obj.method gives a method object with __self__ (the instance) and __func__ (the function); calling it calls __func__(__self__, *args).
  • In Python 3, Class.method is just the plain function; the separate "unbound method" type of Python 2 (which type-checked its first argument) was removed in 3.0.
  • Binding is done by the descriptor protocol: functions define __get__, so attribute lookup through an instance calls function.__get__(obj, type(obj)).
  • Every access creates a new bound method object (obj.m is obj.m is False, but == is True); CPython avoids that allocation for direct calls with LOAD_METHOD (3.11) / LOAD_ATTR method form (3.12+).
  • Bound methods are first-class callables (callbacks, map), and they hold a strong reference to the instance; weakref.WeakMethod avoids keeping it alive.
  • Functions stored on an instance are not bound; types.MethodType binds one by hand.

Code / implementation expected: Optional β€” show type(C.f) vs type(c.f), __self__/__func__, and C.f(c) being the same as c.f().

  • methods
  • binding

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonFunction vs bound method, __self__/__func__, and methods as callbacks
PythonBinding by hand: __get__, types.MethodType, built-in methods, WeakMethod

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 74 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does yield from delegation work?

Continue