Python Create a Class to Simulate a Bank Account Supporting Deposits, Withdrawals and Balance Inquiries
We will create a class named BankAccount class to simulate the basic operations of a bank account. The class will include deposits, withdrawals and balance inquiries. We will use instance variables to store the account balance and provide methods to operate on them.
Example
class
BankAccount:
def
init
(
self
,
owner
,
balance
=
0
)
:
self
.
owner
=
owner
self
.
balance
=
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 >
;
self
.
balance
:
(
"Insufficient funds."
)
elif
amount <
;=
0
:
(
"
;
Withdrawal amount must be positive."
;
)
else
:
self
.
balance
=
amount
(
f"
;
Withdrew
{
amount
}
.
New
balance
is
{
self
.
balance
}
."
;
)
def
get_balance
(
self
)
:
return
self
.
balance
Example usage
account
=
BankAccount
(
"
;
John Doe"
;,
100
)
account.
deposit
(
50
)
account.
withdraw
(
20
)
(
f"
;
Current balance:
{
account.
get_balance
(
)
}
"
;
)
Code analysis:
__init__The method is the class constructor, used to initialize the account owner and balance.owneris the account owner's name,balanceis the account's initial balance, defaulting to 0.depositThe method is used for deposits. It takes an amount; if the amount is positive, it is added to the balance and the new balance is printed. If the amount is negative or zero, an error message is printed.withdrawThe method is used for withdrawals. It checks whether the withdrawal amount is greater than the balance; if so, it prints a message that funds are insufficient. If the amount is positive and does not exceed the balance, the amount is subtracted from the balance and the new balance is printed.get_balanceThe method returns the current account balance.
Output result:
Deposited 50. New balance is 150.
Withdrew 20. New balance is 130.
Current balance: 130
Python3 Examples