Private variables

R

Rasjid Wilcox

Hi all,

I am aware the private variables are generally done via convention
(leading underscore), but I came across a technique in Douglas
Crockford's book "Javascript: The Good Parts" for creating private
variables in Javascript, and I'd thought I'd see how it translated to
Python. Here is my attempt.

def get_config(_cache=[]):
private = {}
private['a'] = 1
private['b'] = 2
if not _cache:
class Config(object):
@property
def a(self):
return private['a']
@property
def b(self):
return private['b']
config = Config()
_cache.append(config)
else:
config = _cache[0]
return config
Traceback (most recent call last):
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b']True

I'm not really asking 'is it a good idea' but just 'does this work'?
It seems to work to me, and is certainly 'good enough' in the sense
that it should be impossible to accidentally change the variables of
c.

But is it possible to change the value of c.a or c.b with standard
python, without resorting to ctypes level manipulation?

Cheers,

Rasjid.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top