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
self.account_namesis actuallyBankAccount.account_names, so all instances ofBankAccountshare exactly the sameaccount_nameslist. Create your list in the__init__method and it'll be an instance variable.self.account_names = []at the top of the__init__method.