class
followed by the class’s name and a colon (:
)# account.py
"""Account class definition."""
from decimal import Decimal
class Account:
"""Account class for maintaining a bank account balance."""
Account?
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"Docstring:"
) and the __init__
method’s docstring ("Init docstring:"
)__init__
¶__init__
method__init__
method that specifies how to initialize an object’s data attributesNone
from __init__
results in a TypeError
Account
’s __init__
method initializes an Account
object’s name
and balance
attributes if the balance
is valid__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
__init__
(cont.)¶self
self
) to access the object’s attributes and other methods__init__
(cont.)¶self.attribute_name `=` value
__init__
(cont.)¶__init__
__
) in the method nameobject
defines the special methods that are available for all Python objects deposit
¶amount
to the account’s balance
attributeValueError
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.