هک‌ها و تشعشعات وجدان آزاد

نوشته‌های سیدمحمدمسعود صدرنژاد

ابزار کاربر

ابزار سایت


courseware:python_programming:resources:answer:23

پاسخ تمرین فروشگاه شی‌گرا

فایل model.py:

from time import strftime
import statistics
 
 
class User:
    """
    User model which includes username of the client
    """
 
    def __init__(self, username: str):
        self.username = username
 
    def __str__(self):
        return self.username
 
 
class Product:
    """
    Product model which includes products' data
    """
 
    num_of_products = 0
 
    def __init__(self, name: str, price: int):
        Product.num_of_products += 1
        self.id = Product.num_of_products
        self.name = name
        self.price = price
        self.quantities = {}
 
    def __str__(self):
        return str((self.id, self.name, self.price))
 
    def add_quantity(self, store, number):
        if store in self.quantities.keys():
            new_quantity = self.quantities[store] + number
            if new_quantity >= 0:
                self.quantities[store] = new_quantity
            else:
                raise Exception('Quantity is not enough!')
        else:
            self.quantities[store] = number
 
    @property
    def quantity(self):
        return sum(self.quantities.values())
 
    def __str__(self):
        return str((self.id, self.name, self.price))
 
 
class Purchase:
    """
    Purchase model includes:
    - Who purchased? user.
    - Which product? product.
    - From which store? store.
    - How many? number.
    - When? date.
 
    And it has a container for all registered purchases.
    """
 
    purchases = list()
 
    def __init__(self, product: Product, store: str, number: int, user: User,
                 date: str = strftime('%Y-%m-%d %H:%M:%S')):
        if product.quantities[store] - number < 0:
            raise Exception('Quantity is not enough!')
        self.product = product
        self.store = store
        self.number = number
        self.user = user
        self.date = date
 
        product.add_quantity(store, -number)
        Purchase.purchases.append(self)
 
    def __str__(self):
        return (str(self.product), self.store, self.number, str(self.user), self.date).__str__()
 
    @classmethod
    def store_revenue(cls, store):
        return sum(
            purchase.product.price * purchase.number
            for purchase in cls.purchases
            if purchase.store == store
        )
 
    @classmethod
    def users_purchased_product(cls, product):
        return [purchase.user for purchase in cls.purchases if purchase.product == product]
 
 
class Comment:
    """
    Comments model includes:
    - who wrote the comment? user.
    - what rate the user is given? rating.
    - comment is written for which product? product.
    - text of the comment? text.
    """
 
    comments = list()
 
    def __init__(self, user: User, product: Product, rating: int, text: str = ''):
        self.user = user
        self.rating = rating
        self.product = product
        self.text = text
        Comment.comments.append(self)
 
    def __str__(self):
        return "user: %s \n product: %s \n rating: %d \n text: %s" % (self.user, self.product, self.rating, self.text)
 
    @classmethod
    def user_comments(cls, user):
        return [comment for comment in cls.comments if comment.user == user]
 
    @classmethod
    def average_rate_purchased_product(cls, product):
        return statistics.mean([comment.rating for comment in cls.comments if comment.product == product])

فایل store.py:

from model import User, Product, Purchase, Comment
 
 
def main():
    done = False
    while not done:
        action = input("""
        1 add user
        2 purchase
        3 add product
        4 add comment
        5 calculate revenue
        6 print users
        7 end
        """)
        done = action == 7
 
    user = User('Masoud')
    product = Product('Gorbe', 1000)
    Purchase(product, 'Sharif', 2, user)
    Comment(user, 5, product, 'Gorbe is good.')
 
 
if __name__ == '__main__':
    main()
courseware/python_programming/resources/answer/23.txt · آخرین ویرایش: 2021/11/08 18:38 توسط smmsadrnezh