Skip to content
Advertisement

python – Object Oriented code for charging

Using python I want to write a code to show deposit and charging of an account. I wrote the following code, but for the charge section I don’t know what/how I should write it, I appreciate it if you could tell me how it should be:

class Account:
    last_id = 1000

    def __init__(self, customer):
        self.customer = customer
        Account.last_id += 1
        self.id = Account.last_id
        self._balance = 0

    def deposit(self, amount):
        

        if amount > 0:
            self._balance += amount
            print('Deposit: ' + str(self._balance))
        else:
            print('Operation was successful')


    def charge(self, amount):
        #This one I am not sure about

Advertisement

Answer

Without a birds eye view of the whole thing, it would be hard to give a definitive answer, but I would imagine charging the customer would be done by checking if the customer’s balance is more than the charged amount, if its not maybe return some sort of message like: “Customer can’t pay the required amount” or make them go into debt. So:

if self._balance < amount:
   print("Customer can't pay the required amount!")
else:
   self._balance = self._balance - amount

or just:

self._balance -= amount

Also as a side note: I don’t recommend asking these sorts of very specific questions, stack overflow is in its own way toxic towards its earlier userbase that asks very specific questions. Try to be more general and use the agreed upon structure of how a question should be asked, using foo bar baz etc.

Advertisement