简体   繁体   English

如何从对象中添加整数变量?

[英]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: 运行代码后,我将在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) 然后,您可以向其中添加amt并在每次调用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. Python支持运算符重载。 In ur case, u can overload add method and then u can type something like a + b. 在您的情况下,您可以重载add方法,然后可以键入a + b之类的内容。

check https://docs.python.org/2/library/operator.html to get more details 检查https://docs.python.org/2/library/operator.html以获得更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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