2017-08-22 3 views
-4

私はシンプルなクラスを持っています。これは私が得た出力である:シンプルクラス - >クラスプロパティの更新

>>> 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", "[email protected]") 
cust2 = Customer("cust2", "8892498598", "[email protected]") 
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) 
+0

ではなく、インスタンス出力として正しい出力を得る: プリント(cust1.amount)= 400、 プリント(cust2.amount)= 600 –

+3

なぜ、 'self.amount'(これは前の行で変更されただけです)を追加していますか? –

答えて

1

変更:

Customer.total_amount += self.amount 

Customer.total_amount += amount 
+1

@RitheshB今、なぜそれが以前にはうまくいかなかったのか考えるべきです。たぶん毎回デバッグして、このコードと前のコードの結果を確認してください。 –

関連する問題