Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’}]

Ledger is created by the 2 methods withdraw and deposit that just append information into ledger each time they’re called.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Obviously withdraws amount are negative and deposits amount are positive, so I wrote this function to get the balance of the class.

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

I created another function percentage_spent where I need the exact same variables of get_balance(Alldeposited, Allwithdrawn), How can I make my code less repetitive? I tried to initialize these variables at the top of the class and inside the constructor but it does not work, I thought that I could create 2 specific method to get the 2 values but at this point it’s better to repeat the code.
The following is the so repetitive code that I wrote.

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

Can you help me?

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading