python-3.x - 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.
解决方案
在方法中添加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
推荐阅读
- ios - 旧版本已经上线时如何提交新版本应用程序?
- awk - 如何用awk小写文件的一部分?
- jqgrid - 升级到 Gurrido 网格 5.5.5 不起作用
- javascript - 如何在反应js URL中传递参数以从api获取数据
- python - 如何在 python 的 html 邮件中嵌入图像?
- php - 选择子查询错误子查询返回超过 1 行
- xml - XQuery 从 XML 文件中删除所有具有属性 onlyChannels="print" 的元素
- ethereum - 找出 ERC20 合约中的地址
- r - R - 数据帧行上的函数错误 True/False
- python - 是否可以在vscode中进入Python shell?