Reputation: 11
import datetime
try:
class Bank:
bank = dict()
bank_preset = 1000
def create_acc(self):
return self.bank_preset + len(self.bank) + 1
def set_details(self,name,pin,mobile="None",transactions=list()):
data_dict = {
"name":name,
"pin":pin,
"balance":0,
"transactions":transactions}
return data_dict
def get_details(self,acc_no,pin):
for k,v in self.bank[acc_no].items():
print(k," -> ",v)
def transaction_preset(self,tr_type, amount, date_time):
tr_preset = {
'tr_type': tr_type,
'datetime': date_time,
'amount': amount,
}
return tr_preset
def deposite(self,acc_no,amount):
data = self.transaction_preset('cr',amount,datetime.datetime.now())
self.bank[acc_no]["transactions"].append(data)
self.bank[acc_no]["balance"] += amount
def withdraw(self,acc_no,amount):
date = datetime.datetime.now()
assert amount < self.bank[acc_no]["balance"],"Insufficient balance."
data = self.transaction_preset('db',amount,datetime.datetime.now())
self.bank[acc_no]["transactions"].append(data)
self.bank[acc_no]["balance"] -= amount
def mini_statement(self,acc_no):
print(" All transactions ".center(60, "-"), end="\n\n")
print("".center(50, "_"))
print("amount".center(15) + "cr/db".center(15) + "date & time".center(15))
print("".center(50, "_"))
for tr_item in selfenter code here.bank[acc_no]['transactions']:
for val in tr_item.values():
print(str(val).center(15), end="")
print("")
except Exception as err:
print(err)
o1 = Bank()
acc_no = o1.create_acc()
acc_data = o1.set_details("Kuldeep",2020)
o1.bank.setdefault(acc_no,acc_data)
o1.deposite(1001,10500)
o1.bank
o2 = Bank()
acc_no = o2.create_acc()
acc_data = o2.set_details("jigar",1010)
o2.bank
In this program i have created bank system by using oops concept. Thing is that when i create new account it will works well but when i deposite or withdraw money from account then all the transactions are copied in all account. Like if i create three account and i want to to add two thousand rupee then this transaction will going to add in another two account. I am trying to solve this problem since 5 days but i couldnot make it up. Please help me.
Upvotes: 1
Views: 58
Reputation: 552
I think it's because you are missing the initialisation method.
A class can have class variables and instance variables. Class variables are accessible to all instances of a class. So every time you create a new bank object, it has access to the same variable.
In this case, the bank
and bank_preset
variables are class variables which are accessed and overwritten by every instance of the class.
On the other hand, instance variables are only accessible for the specific instance of an object.
These are created with the __init__(self)
method.
So you need to add the following method to your class:
def __init__(self, bank: dict, bank_preset: int):
self.bank = bank
self.bank_preset = bank_preset
Then you can initialise each bank as follows:
o1 = Bank({}, 1000)
o2 = Bank({}, 1010)
Upvotes: 1