[Tutor] Instantiating classes

Kirby Urner urnerk@qwest.net
Sun, 31 Mar 2002 18:05:23 -0800


Hi Britt --

This is similar to the Stock class example we were doing
just a few posts ago.  There's also the question of how
to have persistence in your bank accounts between program
sessions, i.e. if you don't output something to a file,
everything goes away.

The shelve module has an interface similar to a dictionary,
meaning you can store objects with names.  You might use
the account number as the dictionary key and shelve your
BankAccount instances by account number when exiting the
program.  Upon starting a new session, these saved
BankAccount instances would be retrievable by the same
key -- convenient for tellers.

However, this is not a super realistic example as in a
real bank you'd want multiple tellers all pulling up and
saving info at the same time, and shelve does not support
concurrent access by multiple users.  So the example here
is more for learning purposes than for actually running
a bank.  A real bank would more likely use a big iron
relational database like Oracle -- so a next step towards
realism in a sandbox would be to use MySQL or something
similar (Python quite capable of serving as a front end).

Anyway, if your teller says 'yes' to add a new account,
you can have something like:

  def addaccount()
       """
       Function for adding new account, called
       from mainmenu()
       """
       accountno   = raw_input("Enter new account number: ")
       accountname = raw_input("Name of account holder  : ")
       balance     = raw_input("Opening balance         : ")

       allaccounts[accountno] = \
          BankAccount(accountno,accountname,balance)

For more details, see (a thread):
http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1093972

And:
http://www.inetarena.com/~pdx4d/ocn/python/stocks.py


Kirby

At 04:46 PM 3/31/2002 -0800, Britt Green wrote:
>Suppose I have a simple class called BankAccount that contains three
>variables: a name, an account number and a balance. When I run my
>program, it asks the bank teller if a new account would like to be
>created. Should the teller say yes, the program would create a new
>instance to the BankAccount class.
>
>My question is this: what's the easiest way to create this new instance
>to the BankAccount class in Python? Obviously the teller can't go into
>the sourcecode everytime she needs to create a new account, but that's
>the only way that I've done it so far.
>
>Many thanks,
>
>Britt