首页 > 解决方案 > I am trying to create a program with class called Product, and the object returns the discount of the price for the number of items purchased

问题描述

I am just a newbie in Python and so far my code looks like this.

class Product:
    def __init__(self,name, amount, price):
        self.name = name
        self.amount = amount
        self.price = price
    def get_price(self,items_cost):
        self.items_cost = items_cost
        if amount < 10:
            items_cost = amount * price
        elif amount >=10 and amount <= 99:
            items_cost = price/10
            items_cost = price-items_cost
        elif amount >= 100:
            items_cost = price/20
            items_cost = price-items_cost
    def make_purchase(self,amount):
        self.price -= amount

name, amount, price = 'books', 200, 33
books = Product(name, amount, price)

amount = 4
items_cost = amount * price
print(f'cost for {amount} {books.name} = {books.get_price(amount)}')
books.make_purchase(amount)
print(f'remaining stock: {books.price}\n')

But when I'm trying to calculate the cost for 4 books, I'm getting the following output

Cost of 4 books = None Remaining Stock: 29

I should get the output cost as 132 for the 4 books purchased.

标签: python-3.x

解决方案


在方法中添加return语句。get_price这将给出输出:

In [44]: class Product:
    ...:     def __init__(self,name, amount, price):
    ...:         self.name = name
    ...:         self.amount = amount
    ...:         self.price = price
    ...:     def get_price(self,items_cost):
    ...:         self.items_cost = items_cost
    ...:         if amount < 10:
    ...:             items_cost = amount * price
    ...:         elif amount >=10 and amount <= 99:
    ...:             items_cost = price/10
    ...:             items_cost = price-items_cost
    ...:         elif amount >= 100:
    ...:             items_cost = price/20
    ...:             items_cost = price-items_cost
    ...:         return items_cost
    ...:     def make_purchase(self,amount):
    ...:         self.price -= amount
    ...:
    ...: name, amount, price = 'books', 200, 33
    ...: books = Product(name, amount, price)
    ...:
    ...: amount = 4
    ...: items_cost = amount * price
    ...: print(f'cost for {amount} {books.name} = {books.get_price(amount)}')
    ...: books.make_purchase(amount)
    ...: print(f'remaining stock: {books.price}\n')
cost for 4 books = 132
remaining stock: 29

推荐阅读