Python: Simple example of creating class and functions in it

class ShoppingCart(object):
“””Creates shopping cart objects
for users of our fine website.”””
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name

def add_item(self, product, price):
“””Add product to the cart.”””
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + ” added.”
print product + ” is already in the cart.”

def remove_item(self, product):
“””Remove product from the cart.”””
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + ” removed.”
print product + ” is not in the cart.”

my_cart = ShoppingCart(“Kedar”)


Tags: ,

2 Responses to “Python: Simple example of creating class and functions in it”

  1. Sujay Kate Says:

    Dude, when I copy-pasted this code in Python’s IDLE, I couldn’t run it as it is, I got some indentation problems as well as some errors related to print method, “Missing parenthesis in call to print”

  2. koolkedar Says:

    Hi Sujay, wordpress has this issue. It removes the indentation/spaces entered. There are many sites which corrects the indentation for you. You can refer those and get the indentation corrected.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: