10.2.2 Account Class Definition

Defining a Class

  • Class definition begins with the keyword class followed by the class’s name and a colon (:)
  • Called the class header
  • Style Guide for Python Code recommends that you begin each word in a multi-word class name with an uppercase letter
  • Every statement in a class’s suite is indented
# account.py
"""Account class definition."""
from decimal import Decimal

class Account:
    """Account class for maintaining a bank account balance."""

Defining a Class (cont.)

  • Each class typically provides a descriptive docstring
  • Must appear in the line or lines immediately following the class header
  • View any class’s docstring in IPython, type the class name and a question mark, then press Enter
In [9]:
Account?
Init signature: Account(name, balance)
Docstring:      Account class for maintaining a bank account balance.
Init docstring: Initialize an Account object.
File:           ~/Dropbox/books/2019/PythonFullThrottle/account.py
Type:           type
Subclasses:     

Defining a Class (cont.)

  • Account is both the class name and the name used in a constructor expression to create an Account object and invoke the class’s __init__ method
  • IPython’s help mechanism shows both the class’s docstring ("Docstring:") and the __init__ method’s docstring ("Init docstring:")

Initializing Account Objects: Method __init__

  • Constructor expression creates a new object, then initializes its data by calling the class’s __init__ method
  • Each new class can provide an __init__ method that specifies how to initialize an object’s data attributes
  • Returning a value other than None from __init__ results in a TypeError
  • Class Account’s __init__ method initializes an Account object’s name and balance attributes if the balance is valid

Initializing Account Objects: Method __init__ (cont.)

def __init__(self, name, balance):
        """Initialize an Account object."""

        # if balance is less than 0.00, raise an exception
        if balance < Decimal('0.00'):
            raise ValueError('Initial balance must be >= to 0.00.')

        self.name = name
        self.balance = balance

Initializing Account Objects: Method __init__ (cont.)

  • When you call a method for a specific object, Python implicitly passes a reference to that object as the method’s first argument
  • So all methods of a class must specify at least one parameter
  • By convention a method’s first parameter is named self
  • Methods must use that reference (self) to access the object’s attributes and other methods

Initializing Account Objects: Method __init__ (cont.)

  • When an object is created, it does not yet have any attributes
  • They’re added dynamically via assignments of the form:
    self.attribute_name `=` value
    

Initializing Account Objects: Method __init__ (cont.)

  • Python classes may define many special methods, like __init__
  • Each identified by leading and trailing double-underscores (__) in the method name
  • Class object defines the special methods that are available for all Python objects

Method deposit

  • Adds a positive amount to the account’s balance attribute
  • Raises a ValueError if amount is less than 0.00
def deposit(self, amount):
        """Deposit money to the account."""

        # if amount is less than 0.00, raise an exception
        if amount < Decimal('0.00'):
            raise ValueError('amount must be positive.')

        self.balance += amount

©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.