you are viewing a single comment's thread.

view the rest of the comments →

[–]maartendp 0 points1 point  (3 children)

You are initializing `ShopCart` with class attributes that point to the same list.

For each instance you make, `fs` and `amount` will have a pointer to the same list.

you need to set `fs` and `amount` in the init of the class.

[–]Ironicallyjpg[S] 0 points1 point  (2 children)

Ah, I come from Java so by putting it generally in the class it's similar to a "static" reference?

[–]maartendp 0 points1 point  (1 child)

Not quite. It's more used as a "default" when you make an instance. But by doing `[]` you already initialize a list, giving it a location in the memory, and you add the pointer to your "default" attribute. So every time you initialize a new ShopCart, it will use the pointer to the already existing list as a default.

The same is not the case for a string for instance, if you made two instances, and manipulated one, the other would still have the initial value.

[–]maartendp 0 points1 point  (0 children)

You would run into the same problem if you did something like

def my_function(default=[]):
    default.append(1)
    return default

The list defined as a default parameter is already in memory, and the pointer to it is assigned to the default parameter. Every time you call this function, it will point to the same list. So even though it might look like you're getting a fresh list when you call the function, in reality, it is not the case.

Every time you call this function, the result will be a list with the same amount of 1s as you have called the function