Reputation: 65
I am having trouble with class level variables. I am trying to figure all I can do with classes. I decided to create a bank account classes and eventually sub-classes but I got hung up on trying to create unique bank accounts.
class BankAccount(object):
"""Creates Bank Account and Functions"""
account_names = []
### Bank Account
import random
class BankAccount(object):
"""Creates Bank Account and Functions"""
account_names = []
def __init__(self, name, balance = 0):
try: # because account_name doesn't exit until the first instnace
for people in account_names: #iterate account names
if people == name: #check if name is in class_var
print "Name already exists!"
break #end instantiation
else: # its a unque name add to the class and object
self.name = name
self.account_names.append(self.name)
except: #First intantition
self.name = name
self.account_names.append(self.name)
self.balance = float(balance)
If I could verify unique self.account
data than I can implement a payment mechanism between bank account holders. However, I can figure out the way to do this. I thought class level vars would do the trick but my out put is:
['Bernie', 'Jerry']
['Bernie', 'Jerry']
['Bernie', 'Jerry', 'Jerry']
Which implies it just appends and therefore an exception has occurred (correct?) why am I still getting an exception the variable exits since it is getting appended to.
Here is a link to the gist
Upvotes: 0
Views: 1711
Reputation: 174624
At a (real) bank, the bank knows information about all of its accounts. Each account has information about the account holder, and the account balance, and transactions; but it doesn't know anything about other customers/accounts.
To transfer money from one account to another, the bank has to be involved.
You need to implement similar things here. Your "bank" can be a class, that holds a collection of other accounts.
class Bank(object):
def __init__(self, name):
self.name = name
self.accounts = [] # Note - this is at the instance level
# so multiple banks don't share each other's accounts
def add_account(self, account):
self.accounts.append(account)
def delete_account(self, account):
try:
self.accounts.remove(account)
except ValueError:
print('{} is already deleted.'.format(account))
def transfer(self, from_acct, to_acct, amount):
if amount < from_account.get_balance():
print('{} is less than the balance of the from account'.format(amount))
to_account.credit(amount)
from_account.debit(amount)
Now, each account holds its own information
class Account(object):
def __init__(self, name, balance):
self.name = name
self.balance = balance
def credit(self, amount):
self.balance += amount
def debit(self, amount):
self.balance -= amount
def get_balance():
return self.balance
Now you can do this:
account_one = Account('John Smith', 500)
account_two = Account('Jane Smith', 100)
bank = Bank("The Bank O'Money")
bank.add_account(account_one)
bank.add_account(account_two)
bank.transfer(account_one, account_two, 10)
bank.accounts # <-- this will be a list of two objects
another_bank = Bank("The Bank of Even More Money")
another_bank.accounts # <-- this will be empty
This kind of pattern - where a bunch of objects should be referred to as one is called the composite pattern because the object is composed of other objects.
The Bank is just a way to refer to a bunch of accounts together.
Upvotes: 0
Reputation: 44609
Class variables are attached to the class, not the instance. This mean they're shared between instances (so in this case the list is the same for all instances).
You can create instances specific variables inside the __init__
method. A simple example:
class BankAccount(object):
def __init__(self):
self.account_names = []
Usually, you won't see the differences between class-level variables and instances-level if you simply use immutables types as class variables (like str, tuple, etc). It's usually a good idea to never set mutable types, like dict
or list
, as class variables.
Upvotes: 1