To what extent can a class "protect" one of it's attributes from outside access?
For example, a class with a conventional _secret attribute, the original value is easily accessed:
class Paranoid(object):
def __init__(self):
self._secret = 0
def set(self, val):
self._secret = val * 10
def get(self):
return self._secret / 10
p = Paranoid()
p.set(123)
print p.get() # 123
print p._secret # 1230, should be inaccessible
How can access to _secret be made more difficult?
There's no practical application to this, I'm just curious if there's novel ways to make it more difficult to access (within the context of Python - so ignoring the fact you could, say, attach a debugger to the Python process and inspect the memory)
You're probably looking for getters and setters. A slightly less complecated approach is to use __secret, which will invoke name mangling to turn it into _Paranoid__secret.
But yes, I should note that the python community doesn't really value privacy the way some languages do. Or as the saying goes we're all consenting adults here.
>>> def Paranoid():
... _secret_dict = {'_secret': 0}
... class ParanoidClass(object):
... def set(self, val):
... _secret_dict['_secret'] = val * 10
... def get(self):
... return _secret_dict['_secret'] / 10
... return ParanoidClass()
...
>>> p = Paranoid()
>>> p.set(123)
>>> p.get()
123
This reminds me of a Steve Yegge blog post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With