Skip to content

Instantly share code, notes, and snippets.

@lamenezes
Created April 15, 2016 02:40
Show Gist options
  • Save lamenezes/536ac64401a1be732c7db19795752545 to your computer and use it in GitHub Desktop.
Save lamenezes/536ac64401a1be732c7db19795752545 to your computer and use it in GitHub Desktop.
"""
>>> f = Foo(1.5, 100)
>>> f._valor
100
>>> f._privado()
150.0
>>>
>>> proxy = Proxy(f)
>>> proxy.publico()
150.0
>>> proxy._privado()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "proxy.py", line 8, in __getattr__
raise AttributeError(msg)
AttributeError: Atributo protegido por '_privado'
>>> proxy._valor
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "proxy.py", line 8, in __getattr__
raise AttributeError(msg)
AttributeError: Atributo protegido por '_valor'
"""
class Proxy:
def __init__(self, embrulhado):
self._embrulhado = embrulhado
def __getattr__(self, attr):
if attr.startswith('_'):
msg = 'Atributo protegido por {0!r}'.format(attr)
raise AttributeError(msg)
else:
return getattr(self._embrulhado, attr)
class Foo:
def __init__(self, tamanho, valor):
self.tamanho = tamanho
self._valor = valor
def _privado(self):
return self.tamanho * self._valor
def publico(self):
return self._privado()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment