Search code examples
pythonclasscreation

Using variables to create class objects


This is my first question on here, so I hope I am asking the 'right' way. The code below is supposed to generate a class object, which should be named via the function createAccount() at the end. I was expecting the account to be a combination of surname and dob, however it creates the class object called accountName and not the product of the variable itself. I can see why it is doing this, but i cannot see how to correct it.

class Account(object):
    def __init__(self, balance):
        self.balance = balance

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

    def withdraw(self,amount):
        if amount <= self.balance:
            self.balance -= amount
            print(self.balance)
            return self.balance
        else:
            print("You do not have sufficient funds for this transaction, please contact your local branch manager")

    def printBalance(self):
        print(self.balance)

def createAccount():
    name = input("Client Surname")
    dob = input("client Date of Birth")
    accountName = name+dob
    print(accountName) # for debug
    accountName = Account(0) # opening account balance is £0
    return accountName

Solution

  • I think what you want is something like a "name" field in your Account object. For example:

    class Account(object):
        def __init__(self, name, balance):
            self.name = name
            self.balance = balance
    
    . . .
    
    def createAccount():
        name = input("Client Surname")
        dob = input("client Date of Birth")
        accountName = name + dob
        print(accountName) # for debug
        account = Account(accountName, 0.0) # opening account balance is £0
        return account
    

    The object returned by createAccount contains both the account balance and the name on the account.