Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Use a Class to Simulate an Online Shopping Cart Supporting Add and Remove Operations

Python Use a Class to Simulate an Online Shopping Cart Supporting Add and Remove Operations

Document Object Reference Manual Python3 Examples

We will use a Python class to simulate an online shopping cart. The cart will support adding products, removing products, viewing its contents and calculating the total price.

Example

class

ShoppingCart:

   

def

init

(

self

)

:

       

self

.

items

=

[

]

   

def

add_item

(

self

,

name

,

price

,

quantity

=

1

)

:

       

self

.

items

.

append

(

{

'name'

: name

,

'price'

: price

,

'quantity'

: quantity

}

)

   

def

remove_item

(

self

,

name

)

:

       

self

.

items

=

[

item

for

item

in

self

.

items

if

item

[

'name'

]

!=

name

]

   

def

view_cart

(

self

)

:

       

if

not

self

.

items

:

           

print

(

"Your shopping cart is empty."

)

       

else

:

           

for

item

in

self

.

items

:

               

print

(

f

"{item['name']} - ${item['price']} x {item['quantity']}"

)

   

def

calculate_total

(

self

)

:

       

return

sum

(

item

[

'price'

]

[

'quantity'

]

for

item

in

self

.

items

)

Example usage

cart

=

ShoppingCart

(

)

cart.

add_item

(

"Apple"

,

0.5

,

3

)

cart.

add_item

(

"Banana"

,

0.3

,

5

)

cart.

view_cart

(

)

print

(

f

"Total: ${cart.calculate_total()}"

)

cart.

remove_item

(

"Banana"

)

cart.

view_cart

(

)

print

(

f

"Total: ${cart.calculate_total()}"

)

Code analysis:

  1. __init__ The method initializes the cart, creating an empty list items to store the products.
  2. add_item The method adds a product to the cart; it takes the product name, price and quantity (default 1) as parameters and adds it to items list.
  3. remove_item The method removes a product with the specified name from the cart, using a list comprehension to filter out the unwanted product.
  4. view_cart The method displays the products in the cart; if the cart is empty it reports that the cart is empty, otherwise it iterates over the items list and prints the details of each product.
  5. calculate_total The method calculates the total price of all products in the cart, implemented with a list comprehension and the sum function.

Output result:

Apple - $0.5 x 3
Banana - $0.3 x 5
Total: $2.4
Apple - $0.5 x 3
Total: $1.5

Document Object Reference Manual Python3 Examples