Last active
July 13, 2017 04:31
-
-
Save wisedier/e115e0b8a13537044fe03b299d829bf5 to your computer and use it in GitHub Desktop.
Access private members each other using decorator as a class instance method
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
# -*- coding:utf-8 -*- | |
class Foo(object): | |
def __init__(self): | |
self.__private_foo = 'private foo' | |
def decorator(self, option): | |
print 'decorator argument:', option | |
print self.__private_foo | |
def set_decorator(func): | |
print func | |
def wrapper(instance, name): | |
private_variable = self.get_private_var(instance, '__private_bar') | |
return 'func result: %s with %s' % (func(instance, name), private_variable) | |
return wrapper | |
return set_decorator | |
def get_private_var(self, instance, name): | |
return getattr(instance, '_%s%s' % (instance.__class__.__name__, name)) | |
foo = Foo() | |
class Bar(object): | |
def __init__(self): | |
self.bar = 'bar' | |
self._protected_bar = 'protected bar' | |
self.__private_bar = 'private bar' | |
@foo.decorator('off') | |
def hello(self, name): | |
return name | |
bar = Bar() | |
print bar.hello('Junsang') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: