Last active
August 14, 2019 08:06
-
-
Save a-recknagel/5789e4ef887b1b9624538ce448eef74c to your computer and use it in GitHub Desktop.
descriptors #1
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 characters
def a(self): | |
return self | |
# write, and optionally modify class A in a way where the following will work | |
inst = A() | |
print(inst.sub.a() is inst) # True | |
# ------------------------------------- instance methods through class binding | |
# if there were no subspace, this would just work: | |
class A: | |
pass | |
A.a = a | |
# we are trying to duplicate the things that are happening under the hood here | |
# as a bonus, the binding happens on class level, so we don't need an __init__ | |
# -------------------------------------------------- Aran Fey's ProxyNamespace | |
class ProxyNamespace: | |
def __init__(self, **attrs): | |
self._attrs = attrs | |
def __get__(self, inst, owner): | |
return Proxy(self._attrs, inst) | |
class Proxy: | |
def __init__(self, namespace, this): | |
self.__namespace = namespace | |
self.__this = this | |
def __getattr__(self, attr): | |
obj = self.__namespace[attr] | |
if hasattr(obj, '__get__'): | |
obj = obj.__get__(self.__this, type(self.__this)) | |
return obj | |
class A: | |
sub = ProxyNamespace(a=a) | |
# ---------------------------------------------- using MethodType and __init__ | |
from types import SimpleNamespace, MethodType | |
class A: | |
def __init__(self): | |
self.sub = SimpleNamespace('a'=MethodType(a, self)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment