Created
January 31, 2017 19:06
-
-
Save 1st1/ebee935256c7cc35c38cc3f73f00461d to your computer and use it in GitHub Desktop.
autosuper
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
class autosuper: | |
_is_bound = object() | |
def __init__(self, meth): | |
self.__meth = meth | |
def __call(meth, inst, owner, args, kwargs): | |
if inst is autosuper._is_bound: | |
result = meth(*args, **kwargs) | |
else: | |
result = meth(inst, *args, **kwargs) | |
supermeth = None | |
for cls in owner.__mro__[1:]: | |
if meth.__name__ in cls.__dict__: | |
supermeth = getattr(cls, meth.__name__) | |
break | |
if supermeth is not None: | |
if inst is autosuper._is_bound: | |
supermeth(*args, **kwargs) | |
else: | |
supermeth(inst, *args, **kwargs) | |
return result | |
def __get__(self, inst, owner): | |
if inst is None: | |
inst = autosuper._is_bound | |
return (lambda *args, **kwargs: | |
autosuper.__call(self.__meth, inst, owner, args, kwargs)) | |
class Base: | |
@autosuper | |
def say(self): | |
print(self, 'BASE') | |
class A(Base): | |
@autosuper | |
def say(self): | |
print(self, 'A') | |
class B(A): | |
@autosuper | |
def say(self): | |
print(self, 'B') | |
B().say() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment