pythonreview

How to not repeat variables inside methods?


the variables self.ledger inside a class displays some deposits and withdraws in this way:

[{'amount': 50, 'description': 'Santa Claus arrived'}, {'amount': -12.5, 'description': 'Thiefs arrived'}]

The 2 methods withdraw and deposit append information into self.ledger each time they're called.

Here is the function to get the balance:

def get_balance(self):
   self.Alldeposited = sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] > 0])
   self.Allwithdrawn = abs(sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] < 0]))
   self.balance = self.Alldeposited - self.Allwithdrawn
   return self.balance

Here is the function to get the percentage spent:

def percentage_spent(self):
    self.Alldeposited = sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] > 0])
    self.Allwithdrawn = abs(sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] < 0]))
    Percentage = round(((self.Allwithdrawn*100)/self.Alldeposited),-1)
    return Percentage

As you can see the code is repetitive, how could I make it less repetitive?


Solution

  • There are two ways to solve this issue: either you keep track, each time you make a transaction, of the total deposited so far, and total withdrawn so far (which is the most efficient), or you simply re-calculate it each time. I would recommend going for the first solution, but since you seem to be recomputing it each time, it must not be a problem for you.

    First solution: recompute it each time

    Using @property, you can make something that looks like an attribute, but whose value is actually computed each time you access it (and you can't write it). Just what we need!

    class Whatever:
       [...]
       @property
       def all_deposited(self):
          return sum(transaction["amount"] for transaction in self.ledger if transaction["amount"] > 0)
       @property
       def all_withdrawn(self):
          return sum(-transaction["amount"] for transaction in self.ledger if transaction["amount"] < 0)
    

    Second solution: keep track of withdrawn and deposited money so far

    class Whatever:
       def __init__(self, ...):
          [...]
          self.all_deposited = 0
          self.all_withdrawn = 0
       [...]
       def deposit(self, amount, ...): # I don't know what the real signature is
          [...]
          self.all_deposited += amount
       def withdraw(self, amount, ...):
          [...]
          self.all_withdrawn += amount
    

    Then, in both cases, you can access these amounts as attributes:

    def percentage_spent(self):
        percentage = round(((self.all_withdrawn*100)/self.all_deposited),-1)
        return percentage
    
    def get_balance(self):
       self.balance = self.all_deposited - self.all_withdrawn
       return self.balance