【问题标题】:Simple Class --> Class property updation简单类 --> 类属性更新
【发布时间】:2017-08-22 12:57:07
【问题描述】:

我有一个简单的课程。这是我得到的输出:

>>> print(Customer.total_amount)
1300

但我预计输出是:

>>> print(Customer.total_amount)
1000

我做错了什么?

class Customer:
    total_amount = 0

    def __init__(self, name, mob, email, amount=None):
        self.name = name
        self.mob = mob
        self.eamil = email
        self.amount = 0

    def add_amount(self, amount):
        self.amount += amount
        Customer.total_amount += self.amount

cust1 = Customer("cust1", "8892398598", "ritheshb1@gmail.com")
cust2 = Customer("cust2", "8892498598", "ritheshb2@gmail.com")
cust1.add_amount(100)
cust2.add_amount(200)
cust1.add_amount(300)
cust2.add_amount(400)

print(cust1.amount)
print(cust2.amount)
print(Customer.total_amount)

【问题讨论】:

  • 但实例输出得到正确输出:print(cust1.amount) = 400, print(cust2.amount) = 600
  • 那你为什么要添加self.amount(刚刚在前一行更改了)?

标签: python class


【解决方案1】:

改变:

Customer.total_amount += self.amount

Customer.total_amount += amount

【讨论】:

    猜你喜欢
    • 2022-11-24
    • 1970-01-01
    • 2011-03-16
    • 2015-11-04
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2020-03-05
    相关资源
    最近更新 更多