Download code

Jump to: navigation, search

Back to Private_class_variables_(Python)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

bank_account.py

 1 # The authors of this work have released all rights to it and placed it
 2 # in the public domain under the Creative Commons CC0 1.0 waiver
 3 # (http://creativecommons.org/publicdomain/zero/1.0/).
 4 # 
 5 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 # 
13 # Retrieved from: http://en.literateprograms.org/Private_class_variables_(Python)?oldid=19190
14 
15 
16 class account(object):
17     def __init__(self, amount):
18         privates = { 'balance' : amount }
19 
20         '''
21         set_balance is a private method
22         it is only visible from other methods declared
23         in the constructor
24         '''
25         def set_balance(new_balance):
26             privates['balance'] = new_balance
27             return
28 
29         '''
30         withdraw is a more normal Python class method
31         '''
32         def withdraw(self, amount):
33             bal = get_balance()
34             if (bal >= amount):
35                 bal = set_balance(bal - amount)
36                 return True
37             else:
38                 return False
39         account.withdraw = withdraw
40 
41         '''
42         get_balance is attached to the
43         instance of the class, so it does not need
44         to take the object self, since it is in the
45         lexical scope
46         '''
47 
48         def get_balance():
49             return privates['balance']
50         self.get_balance = get_balance
51 
52         def deposit(amount):
53             bal = set_balance(get_balance() + amount)
54             return
55         self.deposit = deposit
56 
57         return
58 


hijacker
hijacker
hijacker
hijacker