Skip to content

Instantly share code, notes, and snippets.

@wisedier
Last active July 13, 2017 04:31
Show Gist options
  • Save wisedier/e115e0b8a13537044fe03b299d829bf5 to your computer and use it in GitHub Desktop.
Save wisedier/e115e0b8a13537044fe03b299d829bf5 to your computer and use it in GitHub Desktop.
Access private members each other using decorator as a class instance method
# -*- 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')
@wisedier
Copy link
Author

Result:

$ python decorator.py
decorator argument: off
private foo
<function hello at 0x1005c8410>
func result: Junsang with private bar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment