Created
April 10, 2015 19:27
-
-
Save tritium21/a39174e31569a2383689 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
""" | |
Today I learned... How both super and method binding works. /hack | |
""" | |
import functools | |
import types | |
class Duper(object): | |
""" | |
A very simplistic reimplementation of super(). | |
There are numerous limitations on this, but it works. | |
""" | |
def __new__(cls, typ, obj): | |
self = object.__new__(cls) | |
assert isinstance(obj, typ) | |
self.__obj = obj | |
self.__typ = typ | |
return self | |
def __getattr__(self, name): | |
for base in self.__typ.__mro__[1:]: | |
attr = base.__dict__.get(name, None) | |
if attr is None: | |
continue | |
if isinstance(attr, types.FunctionType): | |
attr = attr.__get__(self.__obj, base) | |
return attr | |
raise AttributeError | |
class FakeMethod(object): | |
""" | |
Knowing what I know now, I can get python to bind instances of my callables | |
like they are methods. It shocked me this works | |
""" | |
def __call__(self, instance): | |
print "do something", instance | |
def __get__(self, instance, cls): | |
return functools.partial(self, instance=instance) | |
class A(object): | |
foo = FakeMethod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Next step... do this