Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing access to "private" attribute in Python

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)

like image 704
dbr Avatar asked Jul 28 '26 02:07

dbr


2 Answers

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.

like image 154
Shep Avatar answered Jul 29 '26 15:07

Shep


>>> 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.

like image 35
vz0 Avatar answered Jul 29 '26 17:07

vz0