Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement a Bank Account Class Supporting Deposits and Withdrawals

Python Implement a Bank Account Class Supporting Deposits and Withdrawals

Document Object Reference Manual Python3 Examples

We will create a simple bank account class containing basic account information such as the account name and balance, and supporting deposit and withdrawal operations.

Example

class

BankAccount:

   

def

init

(

self

,

account_name

,

initial_balance

=

0

)

:

       

self

.

account_name

=

account_name

       

self

.

balance

=

initial_balance

   

def

deposit

(

self

,

amount

)

:

       

if

amount

0

:

           

self

.

balance

=

amount

           

print

(

f

"Deposited {amount}. New balance is {self.balance}."

)

       

else

:

           

print

(

"Deposit amount must be positive."

)

   

def

withdraw

(

self

,

amount

)

:

       

if

amount

0

and

amount

<=

self

.

balance

:

           

self

.

balance

=

amount

           

print

(

f

"Withdrew {amount}. New balance is {self.balance}."

)

       

else

:

           

print

(

"Invalid withdrawal amount."

)

   

def

get_balance

(

self

)

:

       

return

self

.

balance

Example usage

account

=

BankAccount

(

"John Doe"

,

100

)

account.

deposit

(

50

)

account.

withdraw

(

20

)

print

(

f

"Final balance is {account.get_balance()}."

)

Code analysis:

Output result:

Deposited 50. New balance is 150.
Withdrew 20. New balance is 130.
Final balance is 130.

Document Object Reference Manual Python3 Examples