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

2024-05-14 09:42:25 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,如果我有这个代码。我怎样才能把所有的对象加在一起呢?你知道吗

    class saved_money():

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

运行代码后,我会在Python Shell中键入如下内容:

    a = saved_money()
    a = set_amount(100)

可能有任何数量的对象,我想知道是否有一种方法,我可以把它们都加在一起。你知道吗


Tags: 对象代码selfformat键入returndefshell
3条回答

可以使用全局变量:

globalTotal = 0

class saved_money():

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

输出:

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

Python支持操作符重载。在我们的例子中,可以重载add方法,然后可以键入a+b之类的内容

查看https://docs.python.org/2/library/operator.html以获取更多详细信息

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

可以在创建类的实例时创建类变量。然后您可以向它添加amt,并在每次调用set_amount(amt)时返回它

相关问题 更多 >

    热门问题