Zahra
Zahra

Reputation: 11

How to use classes to call for an object using a variable?

I am trying to work on a "keep the change" problem by using object oriented programming on Python. I made a class:

class BankAccount:

    def __init__(self):
        self.savings = 100

    def savings (self, amount):
        self.savings = self.savings + amount
        return self.savings

    def getSavings (self):
        return self.savings

Then I made a separate file to try to take numbers from a file, round them, and then put the difference into the savings account. However, when I call for the savings and try to use a variable to add to the savings, I keep getting an error message stating that it needs to be an int.

def main():

    account1 = BankAccount()

    file1 = open("data.txt","r")
    s = 0       # to keep track of the new savings
    for n in file1:
        n = float(n)    #lets python know that the values are floats
        z= math.ceil(n)         #rounds up to the whole digit
        amount = float(z-n)
        s = int(amount + s)
        x = (account1.savings(s))  # <<this is where the error occurs

Upvotes: 1

Views: 40

Answers (1)

Adarsh Chavakula
Adarsh Chavakula

Reputation: 1599

Your class has an attribute named savings as defined in the __init__ and also a method (function) by the same name. When you reference it the interpreter wouldn't know if you wanted to call the method or get the attribute.

Change the method name from savings to something else, say make_savings

def make_savings(self, amount):

instead of

def savings(self, amount):

Should work

Upvotes: 2

Related Questions