10.2 Custom Class Account

  • Bank Account class that holds an account holder’s name and balance
    • An actual bank account class would likely include lots of other information

10.2.1 Test-Driving Class Account

  • Each new class you create becomes a new data type
  • Python is an extensible language
  • Before we look at class Account’s definition, let’s demonstrate its capabilities

Importing Classes Account and Decimal

  • Launch IPython from the ch10 examples folder, then import class Account
In [1]:
from account import Account
  • Account maintains and manipulates the account balance as a Decimal
In [2]:
from decimal import Decimal

Create an Account Object with a Constructor Expression

  • Create an object with a constructor expression that builds and initializes an object
  • Constructor expressions create new objects and initialize their data using argument(s) specified in parentheses
  • Parentheses following the class name are required, even if there are no arguments
In [3]:
account1 = Account('John Green', Decimal('50.00'))

Getting an Account’s Name and Balance

  • Access the Account object’s name and balance attributes
In [4]:
account1.name
Out[4]:
'John Green'
In [5]:
account1.balance
Out[5]:
Decimal('50.00')

Depositing Money into an Account

  • deposit method receives a positive dollar amount and adds it to the balance
In [6]:
account1.deposit(Decimal('25.53'))
In [7]:
account1.balance
Out[7]:
Decimal('75.53')

Account Methods Perform Validation

  • Account’s methods validate their arguments
In [8]:
account1.deposit(Decimal('-123.45'))
------------------------------------------------------------------------
ValueError                             Traceback (most recent call last)
<ipython-input-8-27dc468365a7> in <module>
----> 1 account1.deposit(Decimal('-123.45'))

~/Dropbox/books/2019/Python/PyCDS_JupyterSlides/ch10/account.py in deposit(self, amount)
     21         # if amount is less than 0.00, raise an exception
     22         if amount < Decimal('0.00'):
---> 23             raise ValueError('amount must be positive.')
     24 
     25         self.balance += amount

ValueError: amount must be positive.

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.