Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Bind Python function as method
# based on:
def bind(instance, func, as_name):
""" Turn a function to a bound method on an instance
.. doctest::
>>> class Foo(object):
... def __init__(self, x, y):
... self.x = x
... self.y = y
>>> foo = Foo(2, 3)
>>> my_unbound_method = lambda self: self.x * self.y
>>> bind(foo, my_unbound_method, 'multiply')
>>> # noinspection PyUnresolvedReferences
... foo.multiply()
:param instance: some object
:param func: unbound method (i.e. a function that takes `self` argument, that you now
want to be bound to this class as a method)
:param as_name: name of the method to create on the object
- creates the new bound method on this instance, like you asked for
setattr(instance, as_name, func.__get__(instance, instance.__class__))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment