{article Examples__Python 3.4 }{title} {text} {/article}
Private Variables In Python
Reference link Properties: attributes managed by get/set methods
Reference link CURRENT
{source}
<!-- You can place html anywhere within the source tags -->
<pre class="brush:py;">
>>> class C(object):
def __init__(self):
self.__x = 0
def getx(self):
return self.__x
def setx(self, x):
if x < 0: x = 0
self.__x = x
x = property(getx, setx)
>>> a = C()
>>> a.x = 10
>>> print (a.x)
10
>>> a.x = -10
>>> print (a.x)
0
>>> a.setx(12)
>>> print (a.getx())
12
>>> class SillyExample(object):
def __init__(self, x):
self._x = x
def get_x(self):
return self._x
def set_x(self, value):
self._x = 2 * value
x = property(get_x, set_x)
>>> silly = SillyExample(2)
>>> print (silly.x)
2
>>> silly.x = 4 # instead of setting x to 4 this will set it to 2 * 4
>>> print (silly.x)
8
>>> def makeSerial(N):
pvt = {'n': 0};
def next_number():
if (pvt['n'] < N):
pvt['n'] += 1;
return pvt['n'];
raise Exception('Ceiling breached.');
return next_number;
>>> next_number = makeSerial(3);
>>> next_number();
1
>>> next_number();
2
>>> next_number();
3
>>> next_number();
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
next_number();
File "<pyshell#28>", line 7, in next_number
raise Exception('Ceiling breached.');
Exception: Ceiling breached.
>>> class Serial(object):
def __init__(self, N):
self._N = N;
self._n = 0;
def next(self):
if (self._n < self._N):
self._n += 1;
return self._n;
raise Exception('Ceiling breached.');
>>> s = Serial(2);
>>> s.next();
1
>>> s.next();
2
>>> s.next();
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
s.next();
File "<pyshell#35>", line 9, in next
raise Exception('Ceiling breached.');
Exception: Ceiling breached.
>>> s._N = 10; # Changing ceiling.
>>> s.next();
3
>>> s.next();
4
>>> s.next();
5
>>> s._n = 1; # Changing order of number-generation.
>>> s.next()
2
>>> s.next()
3
>>> s.next()
4
>>> def makeSerial(N):
pvt = {'n': 0}; # Dictionary of private values.
class Serial(object):
def next(self):
if (pvt['n'] < N):
pvt['n'] += 1;
return pvt['n'];
raise Exception('Ceiling breached.');
return Serial();
>>> s = makeSerial(2);
>>> s.next();
1
>>> s.next();
2
>>> s.next();
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
s.next();
File "<pyshell#49>", line 8, in next
raise Exception('Ceiling breached.');
Exception: Ceiling breached.
>>>
</pre>
<script language="javascript" type="text/javascript">
// You can place JavaScript like this
</script>
<?php
// You can place PHP like this
?>
{/source}