0

For example, if I have this code. How would I get it to add all the objects together?

    class saved_money():

    def set_amount(self, amt):
        self.amount = amt
        return "$"+(format(self.amount, '.2f'))+""

After running the code, I would type something like this in the Python Shell:

    a = saved_money()
    a = set_amount(100)

There could be any amount of objects and I want to know if there is a way I could add them all together.

0

3 Answers 3

1
class saved_money():
    def __init__(self):
        #self.amounts = []
        #or
        self.sumAll = 0

    def set_amount(self, amt):
        #self.amounts.append(amt)
        #return "$"+(format(sum(self.amounts), '.2f'))+""
        #or
        self.sumAll += amt
        return "$"+(format(self.sumAll, '.2f'))+""


a = saved_money()
print a.set_amount(100)
print a.set_amount(200)

>>> $100.00
>>> $300.00

You can create a class variable when creating an instance of your class. Then you can add amt to it and return it everytime you call set_amount(amt)

Sign up to request clarification or add additional context in comments.

Comments

0

You could use a global variable:

globalTotal = 0

class saved_money():

    def set_amount(self, amt):
        global globalTotal
        globalTotal += amt
        self.amount = amt
        return "$"+(format(self.amount, '.2f'))+""

Output:

>>> a = saved_money()
>>> a.set_amount(20)
'$20.00'
>>> globalTotal
20
>>> b = saved_money()
>>> b.set_amount(50)
'$50.00'
>>> globalTotal
70

Comments

0

Python supports operator overload. In ur case, u can overload add method and then u can type something like a + b.

check https://docs.python.org/2/library/operator.html to get more details

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.