Created
June 17, 2020 07:48
-
-
Save purefunctor/cd1c40d65ee08345cd51cb6aabd662c1 to your computer and use it in GitHub Desktop.
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
import functools | |
import types | |
def attrfunc(func=None, **attrs): | |
if not func: | |
return functools.partial(attrfunc, **attrs) | |
return AttrFunc(func, **attrs) | |
class AttrFunc: | |
def __init__(self, func, **attrs): | |
self.func = func | |
for k, v in attrs.items(): | |
setattr(self, k, v) | |
def __call__(self, *args, **kwargs): | |
return self.func(*args, **kwargs) | |
def __get__(self, obj, cls): | |
if obj is None: | |
return self | |
return types.MethodType(self, obj) | |
class Foo: | |
@attrfunc(foo=5, bar=5) | |
def hello(self, x, y): | |
print(x + y) | |
f = Foo() | |
print(f"Attribute {f.hello.foo=}") | |
print(f"Attribute {f.hello.bar=}") | |
f.hello(5, 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment