A list in the __init__ function

Hi everybody,

I am an enthusiastic medical doctor specialized in anesthesia and intensive care medicine and recently got into coding.
My question is the following: what is the practical difference between the position of the ledger list in the 2 examples:

class Category:
def init(self, category, categoryamount=0):
self.category = category
self.categoryamount = categoryamount
self.ledger =

OR

class Category:
def init(self, category, categoryamount=0, ledger=):
self.category = category
self.categoryamount = categoryamount
self.ledger = ledger

Whenever you have a function with a mutable (e.g. list, dict, or set) default argument, that object is created once when the function is declared and then used every time the function is called. In your second example, this means that every Category object that is initialized will share the same ledger object unless a different object is passed in as an argument. This isn’t a problem in the first example because a new list is created every time. It is also not a problem for categoryamount in either example because 0 is immutable.

You can read more about this here.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.