Last active
July 3, 2018 18:52
-
-
Save IwoHerka/4f2fc5ede12e8f3560faa4c91c57bd7e to your computer and use it in GitHub Desktop.
Class decorator for declaring delegated methods
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 Delegated(object): | |
def __init__(self, delegated_name, attr): | |
self.attr_name = attr | |
self.delegated_name = delegated_name | |
def __get__(self, instance, owner): | |
if instance is None: | |
return self | |
else: | |
return getattr(self.delegate(instance), self.attr_name) | |
def __set__(self, instance, value): | |
setattr(self.delegate(instance), self.attr_name, value) | |
def __delete__(self, instance): | |
delattr(self.delegate(instance), self.attr_name) | |
def delegate(self, instance): | |
return getattr(instance, self.delegated_name) | |
class delegate(object): | |
def __init__(self, src, *attrs): | |
self.src = src | |
self.attrs = attrs | |
def __call__(this, cls): | |
for attr in this.attrs: | |
setattr(cls, attr, Delegated(this.src, attr)) | |
return cls | |
class Bar: | |
def grok(self): | |
return 'grok' | |
@delegate('bar', 'grok') | |
class Foo: | |
def __init__(self): | |
self.bar = Bar() | |
foo = Foo() | |
foo.grok() | |
# 'grok' | |
foo.grok = 'bar' | |
foo.grok | |
# 'bar' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Similar to
def_delegator
in Ruby, allows to forward/delegate attributes and methods to some attribute on the object.Supports setting and deleting.