1+ def make_instance (cls ):
2+ """Return a new object instance, which is a dispatch dictionary."""
3+ def get_value (name ):
4+ if name in attributes :
5+ return attributes [name ]
6+ else :
7+ value = cls ['get' ](name )
8+ return bind_method (value , instance )
9+ def set_value (name , value ):
10+ attributes [name ] = value
11+ attributes = {}
12+ instance = {'get' : get_value , 'set' : set_value }
13+
14+ def bind_method (value , instance ):
15+ """Return a bound method if value is callable, or value otherwise."""
16+ if callable (value ):
17+ def method (* args ):
18+ value (instance , * args )
19+ return method
20+ else :
21+ return value
22+
23+ def make_class (attributes , bass_class = None ):
24+ """Return a new class, which is a dispatch dictionary."""
25+ def get_value (name ):
26+ if name in attributes :
27+ return attributes [name ]
28+ elif bass_class is not None :
29+ return bass_class ['get' ](name )
30+ def set_value (name , value ):
31+ attributes [name ] = value
32+ def new (* args ):
33+ return init_instance (cls , * args )
34+ cls = {'get' : get_value , 'set' : set_value , 'new' : new }
35+ return cls
36+
37+ def init_instance (cls , * args ):
38+ instance = make_instance (cls )
39+ init = cls ['get' ]('__init__' )
40+ if init :
41+ init (instance , * args )
42+ return instance
43+
44+ def make_account_class ():
45+ """Return the Account class, which has deposit and withdraw methods."""
46+ interest = 0.02
47+ def __init__ (self , account_holder ):
48+ self ['set' ]('holder' , account_holder )
49+ self ['set' ]('balance' , 0 )
50+ def deposit (self , amount ):
51+ """Increase the account balance by amount and return the new balance."""
52+ new_balance = self ['get' ]('balance' ) + amount
53+ self ['set' ]('balance' , new_balance )
54+ return self ['get' ]('balance' )
55+ def withdraw (self , amount ):
56+ """Decrease the account balance by amount and return the new balance."""
57+ balance = self ['get' ]('balance' )
58+ if amount > balance :
59+ return 'Insufficient funds'
60+ self ['set' ]('balance' , balance - amount )
61+ return self ['get' ]('balance' )
62+ return make_class (locals ())
63+
64+ Account = make_account_class ()
65+
66+ def make_checking_account_class ():
67+ """Return the CheckingAccount class, which imposes a $1 withdrawal fee."""
68+ interest = 0.01
69+ withdraw_fee = 1
70+ def withdraw (self , amount ):
71+ fee = self ['get' ]('withdraw_fee' )
72+ return Account ['get' ]('withdraw' )(self , amount + fee )
73+ return make_class (locals (), Account )
74+
75+ CheckingAccount = make_checking_account_class ()
0 commit comments