-2

So, I'm making a Bank class in python. It has the basic functions of deposit, withdrawing, and checking your balance. I'm having trouble with a transfer method though.

This is my code for the class.

def __init__(self, customerID):
    self.ID = customerID
    self.total = 0

def deposit(self, amount):
    self.total = self.total + amount
    return self.total

def withdraw(self, amount):
    self.total = self.total - amount
    return self.total

def balance(self):
    return self.total

def transfer(self, amount, ID):
    self.total = self.total - amount 
    ID.total = ID.total + amount 
    return ID.balance()

Now, it works, but not the way I want it to. If I write a statement like this, it'll work

bank1 = Bank(111)
bank1.deposit(150)
bank2 = Bank(222)
bank1.transfer(50, bank2)

But I want to be able to use the bank's ID number, not the name I gave it, if that makes any sense? So instead of saying

bank1.transfer(50, bank2)

I want to it say

bank1.transfer(50, 222)

I just have no idea how to do this.

FuzzyMuffin
  • 15
  • 1
  • 1

2 Answers2

1
def __init__(self, customerID):
    self.ID = customerID
    self.__class__.__dict__.setdefault("idents",{})[self.ID] = self
    self.total = 0

@classmethod
def get_bank(cls,id):
    return cls.__dict__.setdefault("idents",{}).get(id)

is one kind of gross way you could do it

bank2_found = Bank.get_bank(222)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

You could store all the ID numbers and their associated objects in a dict with the ID as the key and the object as the value.

Alex
  • 302
  • 3
  • 16