0

Could somebody explain me difference between these two pieces of code? I know that in the second case the arguments can be passed while instansiating the object but my problem was that when I used the 2 option, then the ledger list contained all objects that I have created. With the first one list is unique for the object as expected.

  1. def __init__(self, category):
    
     self.category = category
     self.ledger = []
     self.balance = 0.0
    
  2. def __init__(self, category, ledger = [], balance = 0.0):
    
     # Assign self to object
     self.category = category
     self.ledger = ledger
     self.balance = balance
    
  • 1
    Relevant doc: https://docs.python.org/3/reference/compound_stmts.html#function-definitions. "the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call." – j1-lee Jul 01 '22 at 18:37
  • `ledger = None,` in arguments then `self.ledger = ledger or []` – azro Jul 01 '22 at 18:39

0 Answers0