Reputation: 11
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.
Upvotes: 0
Views: 70
Reputation: 7735
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)
Upvotes: 1
Reputation: 42
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
Upvotes: 0
Reputation: 3485
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
Upvotes: 0