2007-02-03

 

Python学习笔记3--ShoppingApp

class Product:

def __init__(self, name, quantity, price):

self.name = name

self.quantity = quantity

self.price = price

def getName(self):

return self.name

def setName(self, name):

self.name = name

def getQuantity(self):

return self.quantity

def setQuantity(self, quantity):

self.quantity = quantity

def getPrice(self):

return self.price

def setPrice(self, price):

self.price = price

def getValue(self):

return self.quantity * self.price

def __str__(self):

return "\nname:" + self.name + " Quantity:" + str(self.quantity) + " price:" + str(self.price)

class ShoppingCart:

def __init__(self):

self.cart = []

def addProduct(self, product):

self.cart.append(product)

def getTotalValue(self):

ret = 0.0

for proc in self.cart:

ret += proc.getValue()

return ret

def __str__(self):

ret = ""

print "Number of products:" ,len(self.cart)

if len(self.cart) == 0 :

ret = "empty"

else :

for proc in self.cart:

ret += str(proc)

return ret

class ShoppingApp:

def getChoice(self):

try :

choice = int(raw_input("\n[0] Quit"

"\n[1] Add Product"

"\n[2] Display Product"

"\n[3] Display Total"

"\nchoice>" ))

if choice not in range(4 ):

print "Invalid choice, must between 0 and 3."

else :

return choice

except ValueError:

print "Invalid choice, must be an integer."

return 4

def run(self):

self.shopCart = ShoppingCart()

while True :

choice = self.getChoice()

if choice == 0 :

break

elif choice == 1 :

self.shopCart.addProduct(self.getProduct())

elif choice == 2 :

print self.shopCart

elif choice == 3 :

print self.shopCart.getTotalValue()

def getProduct(self):

while True :

proc = raw_input("product [name_qty_price]>" )

tokens = proc.strip().split( "_" )

if len(tokens) != 3 :

print "Invalid input!"

continue

name = tokens[0 ]

try :

qty = int(tokens[1 ])

price = float(tokens[2 ])

if qty < 0 or price < 0.0 :

print "Invalid input."

continue

except ValueError:

print "Invalid input"

continue

return Product(name, qty, price)

#main

ShoppingApp().run()

这个练习是前面两个练习的综合,主要考察的是对基本类的定义,基本的循环结构和控制结构的使用,还有就是对简单异常的处理。通过这个练习,就能熟悉简单的面向对象的编程。需要注意的地方如下:

1 定义容器的时候,最好先初始化,添加对象到容器的方法是append

2 重载对象的__str__方法,可以在以后用str()或者print就能获得该对象的字符串表示。

3 在这里,各个变量的str形式我都用的是str()函数,直接用+不行,这个和java不同,估计还有更好的办法。

4 异常的处理还是简单的ValueError。

5 在处理raw_input的时候,使用了strip,其实不用也可以的。


Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?