简体   繁体   中英

How do you add integer variables from objects?

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.

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM