The other day I learned about 100 Days Of Code, which was popular on Twitter for a while. The purpose of this article is to keep a record and output how much I, as a beginner, can grow through 100 days of study. I think there are many mistakes and difficult to read. I would appreciate it if you could point out!
--Progress: Pages 56-60 --Chapter 3: Classes and Inheritance ――I will write down what I often forget or didn't know about what I learned today.
Records management using dictionaries and tuples is easy to use, but when it becomes complicated, readability is significantly reduced. As an example, define a class that records the sales of a store.
class SimpleSalesRecord(object):
def __init__(self):
self._record = {}
def add_shop_id(self, shop_id):
self._record[shop_id] = []
def report_record(self, shop_id, price):
self._record[shop_id].append(price)
def average_price(self, shop_id):
records = self._record[shop_id]
return sum(records) / len(records)
record = SimpleSalesRecord()
record.add_shop_id(111)
record.report_record(111, 90)
record.report_record(111, 80)
print(record.average_price(111))
Output result
850.0
Consider extending this class to manage sales by product.
class ByitemSalesRecord(object):
def __init__(self):
self._record = {}
def add_shop_id(self, shop_id):
self._record[shop_id] = {} #Change from list to dictionary
def report_record(self, shop_id, item, price):
by_item = self._record[shop_id]
record_list = by_item.setdefault(item, [])
record_list.append(price)
def average_price(self, shop_id):
by_item = self._record[shop_id]
total, count = 0, 0
for prices in by_item.values():
total += sum(prices)
count += len(prices)
return total / count
record = ByitemSalesRecord()
record.add_shop_id(111) # shop_Added a store with id 111
record.report_record(111, 'Apple', 100) #Added 111 store sales
record.report_record(111, 'Apple', 120) #Added 111 store sales
print(record.average_price(111)) #Calculate average sales of 111 stores
Output result
Apple: 110.0
Orange: 90.0
In addition, we will implement a function to discount those with a near expiration date.
class DiscountSalesRecord(object):
def __init__(self):
self._record = {}
def add_shop_id(self, shop_id):
self._record[shop_id] = {} #Change from list to dictionary
def report_record(self, shop_id, item, price, weight):
by_item = self._record[shop_id]
record_list = by_item.setdefault(item, [])
record_list.append((price, weight))
def average_price(self, shop_id):
by_item = self._record[shop_id]
price_sum, price_count = 0, 0
for item, prices in by_item.items():
item_avg, total_weight = 0, 0
for price, weight in prices:
price_sum += price * weight
price_count += 1
return price_sum / price_count
record = DiscountSalesRecord()
record.add_shop_id(111) # shop_Added a store with id 111
record.report_record(111, 'Apple', 100, 0.8) #It's not clear what the positional arguments mean
record.report_record(111, 'Apple', 120, 1)
print(record.average_price(111)) #Calculate average sales of 111 stores
In the average_price method, there is a loop inside the loop, which makes it difficult to read. When this complexity arises, it's time to shift from dictionaries and tuples to the class hierarchy.
The code that refactored the above code into a class is as follows. The named tuple of the collection module is different from a normal tuple and can be specified by a keyword argument.
import collections
Record = collections.namedtuple('Record', ('price', 'weight'))
class Item(object):
def __init__(self):
self._records = []
def report_record(self, price, weight=1):
self._records.append(Record(price, weight))
def average_price(self):
total, total_weight = 0, 0
for record in self._records:
total += record.price * record.weight
return total / len(self._records)
class Shop_ID(object):
def __init__(self):
self._shop_items = {}
def item(self, name):
if name not in self._shop_items:
self._shop_items[name] = Item()
return self._shop_items[name]
def average_price(self):
total, count = 0, 0
for shop_item in self._shop_items.values():
total += shop_item.average_price()
count += 1
return total / count
class SalesRecord(object):
def __init__(self):
self._shop_id = {}
def shop_id(self, name):
if name not in self._shop_id:
self._shop_id[name] = Shop_ID()
return self._shop_id[name]
record = SalesRecord()
shop_111 = record.shop_id(111)
apple = shop_111.item('Apple')
apple.report_record(100, 0.8)
apple.report_record(100)
print(shop_111.average_price())
--Do not create dictionaries whose values are other dictionaries or long tuples --Change to use multiple helper classes when the dictionary becomes complicated
Recommended Posts