Python Implement a Bank Account Class Supporting Deposits and Withdrawals
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
(
f
"Deposited {amount}. New balance is {self.balance}."
)
else
:
(
"Deposit amount must be positive."
)
def
withdraw
(
self
,
amount
)
:
if
amount
0
and
amount
<=
self
.
balance
:
self
.
balance
=
amount
(
f
"Withdrew {amount}. New balance is {self.balance}."
)
else
:
(
"Invalid withdrawal amount."
)
def
get_balance
(
self
)
:
return
self
.
balance
Example usage
account
=
BankAccount
(
"John Doe"
,
100
)
account.
deposit
(
50
)
account.
withdraw
(
20
)
(
f
"Final balance is {account.get_balance()}."
)
Code analysis:
__init__The method is the class constructor, used to initialize the account name and initial balance.depositThe method is used for deposits, increasing the account balance.withdrawThe method is used for withdrawals, decreasing the account balance while ensuring no overdraft.get_balanceThe method returns the current account balance.
Output result:
Deposited 50. New balance is 150.
Withdrew 20. New balance is 130.
Final balance is 130.
Python3 Examples