Last active
April 22, 2023 11:25
-
-
Save carymrobbins/8940382 to your computer and use it in GitHub Desktop.
Partial method for Python 2.7
This file contains 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 characters
from functools import partial | |
class partialmethod(partial): | |
def __get__(self, instance, owner): | |
if instance is None: | |
return self | |
return partial(self.func, instance, | |
*(self.args or ()), **(self.keywords or {})) | |
# Example usage: | |
class C(object): | |
def __init__(self, m): | |
self.m = m | |
def foo(self, x, y): | |
return self.m * (x + y) | |
bar = partialmethod(foo, 1) | |
c = C(2) | |
assert c.foo(1, 2) == 6 | |
assert c.bar(3) == 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. Very useful.