有点接近生产使用。
#!/usr/bin/env python2.7
import types
from pprint import pprint as prn
class Store (object):
def __init__ (self):
self.__stock = {}
@property
def stock (self):
return self.__stock
@stock.setter
def stock (self, products):
"""
Args:
products: {'<title>': [<quantity>, <price>[,
<...>}
"""
if isinstance(products, dict):
self.__stock.update(products)
else:
raise ValueError
def income (self):
stk = self.__stock
return sum((stk[t][0]*stk[t][1] for t in stk))
def __update (self, title, id, value):
if title in self.__stock:
self.__stock[title][id] = float(value)
else:
raise ValueError
def update_quantity (self, title, q):
self.__update(title, 0, q)
def update_price (self, title, p):
self.__update(title, 1, p)
def remove (self, title):
self.__stock.pop(title)
if '__main__' == __name__:
st = Store()
st.stock = {'banana': (6, 4)} # adding the new product
# adding a group of new products
st.stock = {'apple': [0, 2],
'orange': [32, 1.5],
'pear': [15, 3]}
prn(st.stock)
prn(st.income()) # calculating income
st.update_quantity('apple', 1) # updating quantity for apples
prn(st.stock)
prn(st.income())
st.remove('pear') # < removing pears
st.stock = {'grape': [10, 2.5]}
st.update_price('orange', 4.5) # updating price
prn(st.stock)
prn(st.income())
# >>> {'apple': [0, 2], 'banana': (6, 4), 'orange': [32, 1.5], 'pear': [15, 3]}
# >>> 117.0
# >>> {'apple': [1.0, 2], 'banana': (6, 4), 'orange': [32, 1.5], 'pear': [15, 3]}
# >>> 119.0
# >>> {'apple': [1.0, 2], 'banana': (6, 4), 'grape': [10, 2.5], 'orange': [32, 4.5]}
# >>> 195.0