Bifalgorithm post

Imagine recoding a shopping cart and we want to calculate how much a customer will pay for his cart while also allowing for coupons. We'll keep track of coupons and a mapping between item name and the dollar amount of the coupon. The code is simple. We'll loop through each item in the customer's cart, keeping track of total cost. If we notice we can apply a discount, we will apply the discount and remove the coupon so that it only applies one time for that customer. Now, let's say two customers bought an apple by running the following code. Wait, why'd we get two different answers? Each customer bought an apple and had the discount applied. So what gives? The answer lies right here. In Python, when a function is defined, an actual object representing the function is created almost like this. This object, like any other object, has instance variables. One of them is the defaults used in the function. So again, this default is saved once the function is defined, but only once, ever. This means that if we ever manipulate this default, we're manipulating the same object every time.

Imagine recoding a shopping cart and we want to calculate how much a customer will pay for his cart while also allowing for coupons. We'll keep track of coupon…

Ideas in this flowchart

  • Shopping Cart Calculation
  • Track Coupons and Mapping
  • Item-Coupon Mapping
  • Calculate Total Cost
  • Loop Through Items
  • Apply Discount
  • Remove Coupon After Use
  • Issue with Different Results
  • Python Function Object
  • Function Instance Variables
  • Default Saved Once
  • Manipulating Defaults
Feed/

Imagine recoding a shopping cart and we want to calculate how much a customer will pay for his cart while also allowing for coupons. We'll keep track of coupons and a mapping between item name and the dollar amount of the coupon. The code is simple. We'll loop through each item in the customer's cart, keeping track of total cost. If we notice we can apply a discount, we will apply the discount and remove the coupon so that it only applies one time for that customer. Now, let's say two customers bought an apple by running the following code. Wait, why'd we get two different answers? Each customer bought an apple and had the discount applied. So what gives? The answer lies right here. In Python, when a function is defined, an actual object representing the function is created almost like this. This object, like any other object, has instance variables. One of them is the defaults used in the function. So again, this default is saved once the function is defined, but only once, ever. This means that if we ever manipulate this default, we're manipulating the same object every time.

"Imagine recoding a shopping cart and we want to calculate how much a customer will pay for his cart"

👍
0
0 comments0 shares

Sign in to view and post comments.