简单类属性更新

Rit*_*h B 0 python oop class

我有一个课我期待这个:

print(rithesh.amount) = 150.
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

这是我的代码:

class Customer:

    total_amount = 0

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

    def add_amount(self, amount):
        self.amount = amount

rithesh = Customer("Rithesh", "8896398598", "ritheshb1@gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
Run Code Online (Sandbox Code Playgroud)

Ari*_*nda 5

您可以在__init__方法中声明您的金额变量0.然后对您的add_amount方法进行一些小改动.

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

    rithesh = Customer("Rithesh", "8896398598", "ritheshb1@gmail.com")
    rithesh.add_amount(100)
    rithesh.add_amount(50)
    print(rithesh.amount)
Run Code Online (Sandbox Code Playgroud)

产量

150
Run Code Online (Sandbox Code Playgroud)