python – Object Oriented code for charging

Question:

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
Asked By: Mery p.

||

Answers:

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.

Answered By: Dimitur Karabuyukov

I would recommend making the _balance variable private by using double underscore __balance.

You can implement the charge method as follows:

def charge(self, amount):
    if self.__balance < amount:
        print("Not enough balance")
    else:
        self.__balance = self.__balance - amount

Other suggestions I would like to provide are –

  1. Make the other variables like customer private and implement getter and setter methods for them.

  2. While writing OOPs code, make use of self-explanatory names for variables. One of the suggestions is already given by @Gameplay in the comments.

Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.