Rithesh B Rithesh B - 1 month ago 10
Python Question

Simple class Property Update

I have a class where I'm expecting this:

print(rithesh.amount) = 150.


How can I do this?

Here is my code:

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)

Answer Source

You can declare your amount variable in your __init__ method as 0. Then make a small change in your add_amount method.

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)

output

150