Created
February 11, 2015 01:42
-
-
Save floer32/a928b801ca5c7705e94e to your computer and use it in GitHub Desktop.
Revisions
-
floer32 created this gist
Feb 11, 2015 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,26 @@ # based on: http://stackoverflow.com/questions/1015307/python-bind-an-unbound-method#comment8431145_1015405 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() 6 :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 SIDE EFFECTS: - creates the new bound method on this instance, like you asked for """ setattr(instance, as_name, func.__get__(instance, instance.__class__))