首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Python打印收银机收据

问用Python打印收银机收据
EN

Code Review用户
提问于 2021-03-27 19:01:39
回答 2查看 2.5K关注 0票数 8

问题

输出购买物品的收据。投入:

  • products_text_path:产品可以在<barcode>:<name>:<price>行格式的文本文件中找到。
  • purchased_items_set:购买的物品作为整数条形码的列表给出。同一物品被发现了好几次。
  • discount_rules_text_path:文本文件中有<barcode>:<min_quantity>:<discount>格式的折扣规则,这意味着购买超过min_quantity的barcode项目会给您一个discount (作为折扣百分比/1)。

目标

处理大量输入的可读代码

示例

代码语言:javascript
复制
Products:
- 123:banana:0.5
- 789:apple:0.4

Discounts:
- 123:2:0.2 # Meaning buying 2 bananas will add a 20% discount

Purchases:
- [123,123] # Bought 2 bananas

Output:
- [('banana', 2, 0.8)]

在

下面代码中可能出现的问题

  • 我把所有的信息都保存在记忆里。
  • 我可能使用了太多的类来表示不同的信息片段?

码

从start_process函数开始读取代码时,最好能理解代码

代码语言:javascript
复制
class Product:
  def __init__(self, barcode: int, name: str, price: float):
    self.bardcode = barcode
    self.name = name
    self.price = price

  @classmethod
  def parse_product(cls, product_line: str):
    name, barcode_str, price_str = product_line.split(':')
    price = float(price_str)
    barcode = int(barcode_str)
    return cls(barcode, name, price)

class Products:
  def __init__(self):
    self.products = {} # Type: Dict<int, Product>

  def add_product(self, product: Product):
    self.products[product.bardcode] = product

  def get_product(self, product_barcode):
    return self.products[product_barcode]

  @classmethod
  def parse_products(products_cls, products_path: str):
    products = products_cls()
    with open(products_path) as products_lines:
      for product_line in products_lines:
        product = Product.parse_product(product_line)
        products.add_product(product)
    return products

class ProductPurchase:
  def __init__(self, barcode: int, quantity = 1, discount = 0.0):
    self.barcode = barcode
    self.quantity = quantity
    self.discount = discount

class DiscountRule:
  def __init__(self, product_barcode: int, min_quantity: int, discount_amount: float):
    self.product_barcode = product_barcode
    self.min_quantity = min_quantity
    self.discount_amount = discount_amount

  @classmethod
  def parse(cls, discount_rule: str):
    barcode_str, min_quantity_str, discount_amount_str = discount_rule.split(':')
    return cls(int(barcode_str), int(min_quantity_str), float(discount_amount_str))

class DiscountRules:
  def __init__(self):
    self.dicounts = {} # Type: Dict<int, DiscountRule>

  def add_discount(self, discount: DiscountRule):
    self.dicounts[discount.product_barcode] = discount

  def apply_discount(self, purchase: ProductPurchase):
    if purchase.barcode not in self.dicounts:
      return
    discount = self.dicounts[purchase.barcode]
    if purchase.quantity < discount.min_quantity:
      return
    purchase.discount = discount.discount_amount

  @classmethod
  def parse_discount_rules(cls, rules_path: str):
    rules = cls()
    with open(rules_path) as rules_lines:
      for rule_line in rules_lines:
        rule = DiscountRule.parse(rule_line)
        rules.add_discount(rule)
    return rules


class Purchases:
  def __init__(self):
    self.purchases = {} # Type: Dict<int, ProductPurchase>

  def add_purchase(self, purchased_barcode: int):
    if purchased_barcode in self.purchases:
      self.purchases[purchased_barcode].quantity += 1
    else:
      self.purchases[purchased_barcode] = ProductPurchase(purchased_barcode)

  def get_purchases(self):
    for purchase in self.purchases.values():
      yield purchase


class Checkout:
  def __init__(self, purchases: Purchases, products: Products, discount_rules: DiscountRules):
    self.purchases = purchases
    self.products = products
    self.discount_rules = discount_rules

  def check_out(self):
    result = []
    for purchase in self.purchases.get_purchases():
      self.discount_rules.apply_discount(purchase)
      product = self.products.get_product(purchase.barcode)
      price = _calculate_price(product.price, purchase.quantity, purchase.discount)
      result.append((product.name, purchase.quantity, price))

    return result

def _calculate_price(price, quantity, discount):
  return str(round(price * quantity * (1.0 - discount), 2))

def start_process(products_paths: str, discounts_path: str, scanner_input):
  purchases = Purchases()
  for purchased_barcode in scanner_input:
    purchases.add_purchase(purchased_barcode)

  products = Products.parse_products(products_paths)
  discount_rules = DiscountRules.parse_discount_rules(discounts_path)
  checkout = Checkout(purchases, products, discount_rules)

  return checkout.check_out()
EN

回答 2

Code Review用户

发布于 2021-03-27 21:03:05

  • 缩进不是4的倍数,而PEP8确定它应该。
  • 没有指向脚本的入口(如果__名称为__ == '__ main _“.)。
  • Parse_product是在条形码之前得到名称的,而确定顺序的问题是相反的。
  • 类产品基本上是一本字典。仅为parse_products类方法只包含一个字典(实际上并不公开它的所有有用的接口)对我来说没有任何意义。我看到了4个选项:从dict继承,至少它是一个适当的dict,有ProductUtils,只有实用程序函数parse_products,或者有一个函数parse_products,在Products中有parse_products实用程序,不需要有parse_products(如果产品基本上是一个dict)。在我看来他们都好多了。
  • 计算价格是没有意义的,因为它是一个效用函数。如果它计算购买的折扣价格,为什么不让它在购买类中?
  • 你有从事DBs工作的背景吗?ProductPurchase结构在数据库上下文中是有意义的。但是在这个面向对象的设计中,为什么不只是拥有ProductCart呢?另外,不要存储条形码,而是存储实际的产品(我们不会为我们已经拥有的单个对象引用腾出太多空间,而且它将比拥有它的密钥更有用)!
  • 同样地,购买也只是一个小问题,所以为什么不继承它来获得它的全部效用,而只是忽略了我们需要改变的东西。而且,add_purchase是误导的,因为您添加了产品/条形码,而不是购买(因为购买是在方法中生成的)。
  • 在我看来,DiscountRules课程是不必要的。为什么不将折扣存储在Product本身?
  • 通常,任何方法中都没有文档字符串,任何地方都没有注释。
  • check_out方法基本上只需要通过购买就可以了。从本质上说,它什么也不做,因此不需要它。
  • 代码中的其他注释

这是我建议的最后一个版本:

代码语言:javascript
复制
from typing import Iterable, Dict


class Product:
    def __init__(self, barcode: int, name: str, price: float):
        self.barcode = barcode
        self.name = name
        self.price = price
        self.discounts = []

    @classmethod
    def parse_product(cls, product_line: str):
        barcode, name, price = product_line.split(':')
        return cls(int(barcode), name, float(price))

    def add_discount(self, discount: 'DiscountRule'):
        self.discounts.append(discount)


class Products(dict):
    def __init__(self, *args, **kwargs):
        super(Products, self).__init__(*args, **kwargs)

    def add_product(self, product: Product):
        self[product.barcode] = product

    @classmethod
    def parse_products(cls, products_path: str, discount_rules: 'Dict[int, DiscountRule]'):
        products = cls()
        with open(products_path) as products_lines:
            for product_line in products_lines:
                product = Product.parse_product(product_line)

                if product.barcode in discount_rules:
                    product.add_discount(discount_rules[product.barcode])

                products.add_product(product)
        return products


class ProductPurchase:
    def __init__(self, product: Product, quantity: int = 1):
        self.product = product
        self.quantity = quantity

    @property
    def discount(self):
        total_discount = None
        for discount in self.product.discounts:
            if self.quantity >= discount.min_quantity:
                if total_discount is None:
                    total_discount = 0
                total_discount += discount.discount_amount
        return total_discount

    def purchase(self, quantity: int = 1):
        self.quantity += quantity

    @property
    def discounted_price(self):
        return round(self.product.price * self.quantity * (1.0 - self.discount), 2)


class DiscountRule:
    def __init__(self, product_barcode: int, min_quantity: int, discount_amount: float):
        self.product_barcode = product_barcode
        self.min_quantity = min_quantity
        self.discount_amount = discount_amount

    @classmethod
    def parse(cls, discount_rule: str):
        barcode_str, min_quantity_str, discount_amount_str = discount_rule.split(':')
        return cls(int(barcode_str), int(min_quantity_str), float(discount_amount_str))

    @classmethod
    def parse_discount_rules(cls, rules_path: str) -> 'Iterable[int, DiscountRule]':
        with open(rules_path) as rules_lines:
            for rule_line in rules_lines:
                discount_rule = DiscountRule.parse(rule_line)
                yield discount_rule.product_barcode, discount_rule


class Purchases(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def purchase(self, product: Product):
        if product.barcode in self:
            self[product.barcode].purchase()
        else:
            self[product.barcode] = ProductPurchase(product)


class ShoppingCart:
    def __init__(self, purchases: Purchases, products: Products):
        self.purchases = purchases
        self.products = products

    @classmethod
    def init_from_files(cls, products_path: str, discounts_path: str, scanner_input: list):
        discount_rules = DiscountRule.parse_discount_rules(discounts_path)

        products = Products.parse_products(products_path, dict(discount_rules))

        purchases = Purchases()
        for purchased_barcode in scanner_input:
            purchases.purchase(products[purchased_barcode])

        return cls(purchases, products)


if __name__ == "__main__":
    cart = ShoppingCart.init_from_files("products.txt", "discounts.txt", [123, 123])

    print("TICKET")
    for purchase in cart.purchases.values():
        print("%s x %s | %s€" % (purchase.quantity, purchase.product.name, purchase.discounted_price))
    print("------")

以及带有注释的代码:

代码语言:javascript
复制
from typing import Iterable, List


class Product:
    def __init__(self, barcode: int, name: str, price: float):
        self.barcode = barcode  # bardcode seems a typo for barcode
        self.name = name
        self.price = price
        self.discounts = []

    @classmethod
    def parse_product(cls, product_line: str):
        barcode, name, price = product_line.split(':')
        """price = float(price_str)
        barcode = int(barcode_str) >>> un-needed in two steps """
        return cls(int(barcode), name, float(price))

    def add_discount(self, discount: 'DiscountRule'):
        self.discounts.append(discount)


class Products(dict):
    def __init__(self, *args, **kwargs):
        super(Products, self).__init__(*args, **kwargs)

    def add_product(self, product: Product):
        self[product.barcode] = product

    """def get_product(self, product_barcode):
        return self[product_barcode]
        
        >>> no need for this method, the dict already implements a get
        """

    @classmethod
    def parse_products(cls, products_path: str):
        """stick to the cls naming convention
        since it is a class method from the Products class, it is trivial that it is a product_cls
        """
        products = cls()
        with open(products_path) as products_lines:
            for product_line in products_lines:
                product = Product.parse_product(product_line)
                products.add_product(product)
        return products


class ProductPurchase:
    def __init__(self, product: Product, quantity: int = 1):  # >>> type hinting missing
        self.product = product
        self.quantity = quantity
        # self.discount = discount
        """
        >>> instead of storing a hard copy of the discount, which might get corrupted
            if the discount or quantity change, use a property and compute it live
        """

    @property
    def discount(self):
        """ computes the discount, accepts multiple discounts per product now """
        total_discount = None
        for discount in self.product.discounts:
            if self.quantity >= discount.min_quantity:
                if total_discount is None:
                    total_discount = 0
                total_discount += discount.discount_amount
        return total_discount

    def purchase(self, quantity: int = 1):
        """ provide a nice interface for modifying the quantity """
        self.quantity += quantity

    @property
    def discounted_price(self):
        return round(self.product.price * self.quantity * (1.0 - self.discount), 2)


class DiscountRule:
    def __init__(self, product_barcode: int, min_quantity: int, discount_amount: float):
        self.product_barcode = product_barcode
        self.min_quantity = min_quantity
        self.discount_amount = discount_amount

    @classmethod
    def parse(cls, discount_rule: str):
        barcode_str, min_quantity_str, discount_amount_str = discount_rule.split(':')
        return cls(int(barcode_str), int(min_quantity_str), float(discount_amount_str))

    @classmethod
    def parse_discount_rules(cls, rules_path: str) -> 'Iterable[DiscountRule]':
        with open(rules_path) as rules_lines:
            for rule_line in rules_lines:
                yield DiscountRule.parse(rule_line)

    @classmethod
    def add_discounts_to_products(cls, discounts: 'Iterable[DiscountRule]', products: Products):
        for discount in discounts:
            if discount.product_barcode in products:
                products[discount.product_barcode].add_discount(discount)


class Purchases(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def purchase(self, product: Product):  # work with objects! not with keys which refer to objects
        if product.barcode in self:
            self[product.barcode].purchase()
        else:
            self[product.barcode] = ProductPurchase(product)

    """def get_purchases(self):
        for purchase in self.values():
            yield purchase
            >>> not needed since now the interface is the actual dict
            """


class ShoppingCart:  # a more meaningful name to the object, check_out is an action/method
    def __init__(self, purchases: Purchases, products: Products):
        self.purchases = purchases
        self.products = products
        # self.discount_rules = discount_rules  >>> not needed anymore

    def check_out(self) -> Iterable:
        """ return an iterable instead of a list, the caller can then do whatever xhe wants """
        for purchase in self.purchases.values():
            yield purchase.product.name, purchase.quantity, purchase.discounted_price

    @classmethod
    def init_from_files(cls, products_path: str, discounts_path: str, scanner_input: list):
        # get products from products_path
        products = Products.parse_products(products_path)

        # get discount_rules from discount_path
        discount_rules = DiscountRule.parse_discount_rules(discounts_path)
        DiscountRule.add_discounts_to_products(discount_rules, products)

        purchases = Purchases()
        for purchased_barcode in scanner_input:
            purchases.purchase(products[purchased_barcode])

        return cls(purchases, products)




"""def get_checkout(products_paths: str, discounts_path: str, scanner_input):
    
    >>> if all the code is using objects, why have a random function and not use those objects?
"""

if __name__ == "__main__":
    cart = ShoppingCart.init_from_files("products.txt", "discounts.txt", [123, 123])
    print(list(cart.check_out()))
票数 3
EN

Code Review用户

发布于 2021-03-28 14:50:14

因为您正在处理CSV数据,而且如果您有一个结构良好的文件,就没有必要重新发明轮子并自己进行解析。Python已经有了一个用于此目的的库:csv - CSV文件读写。当然,一个个人的和极简的实现能够比一个已经建立并经过时间证明的模块表现得更好,这并不是不可能的,但这是值得怀疑的。但你可以自己测试。

另一个更明显的选择是使用熊猫。将数据导入dataframe,可以根据计算结果进一步操作该数据。

你还有一个选择:数据库。您可以使用sqlite模块并将文件导入到表中。我认为这个选择很适合你的目的。您可以通过几个联接完成工作,并可能根据需要进行一些子选择。但在这里,这只是您需要的3个表的一个非常基本的连接。

SQLite可以批量导入CSV文件,但是您需要为此调用shell。参见例如:https://wizardforcel.gitbooks.io/sqlite-doc-en/content/30.html

注意:数据库文件甚至不需要存储在磁盘上,您可以创建一个内存中的DB,在程序执行后被释放。但是,如果您有大型数据集,并且担心内存消耗,那么请使用DB文件。如果您在Linux上,可以在/tmp上使用临时文件,它通常是tmpfs (=快速数据访问)。

无论哪种方式,当所有数据都已导入时,批量执行计算(回扣)会更容易。您可以创建视图、临时表等。如果需要变得更加复杂,则可以使用Python混合使用,或者选择一个支持存储过程的数据库来处理更复杂的计算。

我不认为你选择的方法是最佳的。至少我建议您将编码中的这两个关注点分开:数据的导入和数据的转换。我的建议是重新考虑可用于这项工作的工具。在我看来,如果您选择DB方法,您可以抛弃这些类,并大大简化工作。

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/258775

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档