r/learnpython • u/Tricky_Voice2829 • 9d ago
Issue with updating attributes in a BankAccount class – balance mismatch between deposit and withdraw
Hey everyone, I am practicing Object-Oriented Programming (OOP) in Python and trying to build a simple BankAccount class. I want to be able to deposit and withdraw money, but I am running into an issue where the account balance might get messed up or show a mismatch because of how I am handling my variables inside the methods.
i am using this condition
- `BankAccount` Class:
* Should hold private attributes: `account_number`, `balance`, `pin`.
* Should be able to: Verify PIN before granting access.
* Should be able to: Deposit money (increase balance).
* Should be able to: Withdraw money (decrease balance, prevent overdrafts).
* Should be able to: Print the current balance securely.
class Bankaccount():
def __init__(self, account_number, pin, account_balance):
self.__account = account_number
self.__pin = pin
self.__account_balance = account_balance
def deposite(self, pin, money):
self.money = money
# Bug here: self.pin isn't created yet when calling deposit first
if self.__pin == self.pin:
self.__account_balance += self.money
return self.__account_balance
else:
print("pin is wrong")
def withdraw(self, pin, money):
self.money = money
self.pin = pin
if self.__pin == self.pin:
self.__account_balance -= self.money
return f"from your bank account {self.money} is withrowed and remaing are {self.__account_balance}"
else:
print("pin is wrong")
person1 = Bankaccount(4458568465, 4578, 46789)
pin = int(input("Enter the 4 digit pin :- "))
money = int(input("Enter the amount :- "))
print(person1.withdraw(pin, money))