Chương trình cung cấp các mục, có người dùng trả tiền cho các mặt hàng, 'đưa ra' các mục. Nó dường như hoạt động ít nhiều. Tôi có 2 câu hỏi:
Tôi không biết làm thế nào để khấu trừ tiền mặt từ tiền mặt nó được gửi và khi họ chọn mặt hàng, nó sẽ phát hiện tiền mặt từ khoản tiền gửi và trả lại phần còn lại của những thay đổi
Có cách nào để làm cho mã đơn giản hơn/tốt hơn không?
import time
import sys
class CashBox[object]:
def __init__[self]:
self.credit = 0
self.totalReceived = 0
#self.price = 35
def deposit[self, amount]:
self.credit = amount + self.credit
self.totalReceived = amount + self.totalReceived
print["Depositing {0} cents. You have {1} cents credit.".format[
amount, self.credit]]
# print[type[self.credit]]
return self.credit
def returnCoins[self]:
print["Returning ", self.credit/100, " dollars."]
self.totalReceived = 0
def haveYou[self, name, price, recipe]:
return self.credit >= price
def deduct[self, amount]:
pass
def totalCoins[self]:
return self.totalReceived
class CoffeeMachine[object]:
def __init__[self]:
self.cashBox = CashBox[]
self.credit = CashBox.__init__
self.selector = self.cashBox
def oneAction[self]:
while True:
command = input["""
______________________________________________________
PRODUCT LIST: all 35 cents, except bouillon [25 cents]
1=black, 2=white, 3=sweet, 4=sweet & white, 5=bouillon
Sample Commands: insert 25, select 1, cancel, quit.
Your command:
"""]
words = command.lower[].split[]
if 'select' in words:
Selector.select[self, int[words[1]]]
elif 'insert' in words:
coinsAllowed = [5, 10, 25, 50]
if int[words[1]] in coinsAllowed:
self.cashBox.deposit[int[words[1]]]
else:
print[
"""We only take half-dollars, quarters, dimes, and nickels."""]
elif 'cancel' in words:
print["Cancelling transaction. Returning to main menu: "]
self.cashBox.returnCoins[]
elif 'quit' in words:
break
else:
print["Invalid command."]
def totalCash[self]:
return self.cashBox.totalReceived
class Product[object]:
def __init__[self, name, price, recipe]:
self.name = name
self.price = price
self.recipe = recipe
def getPrice[self]:
return self.price
def make[self]:
for item in self.recipe:
print["dispensing", item]
time.sleep[0.5]
print["Enjoy your", self.name]
time.sleep[0.5]
# print[self.price]
class Selector[object]:
def __init__[self]:
#self.Product = Product[]
self.cashBox = CashBox[]
self.credit = CashBox.deposit
# self.products.append[Product.
def select[self, choiceIndex]:
recipes = {
1: ["Black coffee", 35, ["cup", "coffee", "water"]],
2: ["White coffee", 35, ["cup", "coffee", "creamer", "water"]],
3: ["Sweet coffee", 35, ["cup", "coffee", "sugar", "water"]],
4: ["White & Sweet coffee", 35, ["cup", "coffee", "sugar", "creamer", "water"]],
5: ["Bouillon", 25, ["cup bouillonPowder", "water"]]
}
if choiceIndex in range[1, len[recipes]+1]:
self.choiceIndex = choiceIndex
self.recipe = recipes.get[choiceIndex]
product = Product[*self.recipe]
if self.cashBox.haveYou[*self.recipe] == True:
#print[self.recipe,"Great selection"]
#price = CashBox.haveYou[*self.recipe]
product.make[]
self.cashBox.haveYou = self.cashBox.haveYou - self.cashBox.deduct
print["Returning {0} cents.".format[self.cashBox.haveYou]]
else:
print["Sorry. Not enough money deposited."]
else:
print["That selection does not exist"]
def main[]:
m = CoffeeMachine[]
while m.oneAction[]:
pass
total = m.totalCash[]
print[f"Total cash received: ${total/100:.2f}"]
if __name__ == "__main__":
main[]
Đừng sleep
- nó không giúp người dùng trải nghiệm.
Đừng thừa kế từ object
vì đó là một Python 2-ism.
Tôi không nghĩ rằng bạn đối xử với credit
và totalReceived
đủ khác để biện minh cho người sau; Nó chỉ nên biến mất.
Xem xét thay thế các cuộc gọi định dạng của bạn bằng F-String.
haveYou
là một cái tên hơi khó hiểu - có thể gọi nó là has_credit_for
?
Tên phương thức của bạn - haveYou
, v.v. - phải là Lower_Snake_case, như trong ____10.
print["Returning {0} cents.".format[self.cashBox.haveYou]]
1 là sự khởi đầu cho một phương pháp hợp lý nhưng không bao giờ được thực hiện?print["Returning {0} cents.".format[self.cashBox.haveYou]]
2 và các phương pháp getter mỏng tương tự có thể bị xóa. Nói chung, các biến thành viên công cộng vắng mặt có nhiều pythonic hơn.Việc gán
print["Returning {0} cents.".format[self.cashBox.haveYou]]
3 cho một biến không có ý nghĩa. Đừng làm điều này.Danh sách
print["Returning {0} cents.".format[self.cashBox.haveYou]]
4 phải là một tập hợp print["Returning {0} cents.".format[self.cashBox.haveYou]]
5 do cách nó được sử dụng.print["Returning {0} cents.".format[self.cashBox.haveYou]]
6 có thể được khởi tạo trong quá trình xây dựng biến print["Returning {0} cents.".format[self.cashBox.haveYou]]
7 của bạn, cần được lưu trữ dưới dạng tĩnh.print["Returning {0} cents.".format[self.cashBox.haveYou]]
8 không nên được lưu trữ trên lớp. Tương tự như vậy đối với print["Returning {0} cents.".format[self.cashBox.haveYou]]
9.Bạn có một phương thức
from typing import NamedTuple
class CashBox:
def __init__[self] -> None:
self.credit = 0
def deposit[self, amount: int] -> None:
self.credit += amount
print[f"Depositing {amount} cents. You have {self.credit} cents credit."]
def return_coins[self] -> None:
print[f"Returning {self.credit / 100} dollars."]
self.credit = 0
def has_credit_for[self, price: int] -> bool:
return self.credit >= price
def deduct[self, amount: int] -> None:
self.credit -= amount
class Product[NamedTuple]:
name: str
price: int
recipe: list[str]
def make[self]:
for item in self.recipe:
print["dispensing", item]
print["Enjoy your", self.name]
class CoffeeMachine:
RECIPES = [
Product[*args]
for i, args in enumerate[
[
["Black coffee", 35, ["cup", "coffee", "water"]],
["White coffee", 35, ["cup", "coffee", "creamer", "water"]],
["Sweet coffee", 35, ["cup", "coffee", "sugar", "water"]],
["White & Sweet coffee", 35, ["cup", "coffee", "sugar", "creamer", "water"]],
["Bouillon", 25, ["cup bouillonPowder", "water"]],
], 1
]
]
def __init__[self] -> None:
self.cash_box = CashBox[]
def one_action[self] -> bool:
command = input["""
______________________________________________________
PRODUCT LIST: all 35 cents, except bouillon [25 cents]
1=black, 2=white, 3=sweet, 4=sweet & white, 5=bouillon
Sample Commands: insert 25, select 1, cancel, quit.
Your command:
"""]
words = command.lower[].split[]
if 'select' in words:
self.select[int[words[1]]]
elif 'insert' in words:
amount = int[words[1]]
coins_allowed = {5, 10, 25, 50}
if amount in coins_allowed:
self.cash_box.deposit[amount]
else:
print["We only take half-dollars, quarters, dimes, and nickels."]
elif 'cancel' in words:
print["Cancelling transaction. Returning to main menu: "]
self.cash_box.return_coins[]
elif 'quit' in words:
return False
else:
print["Invalid command."]
return True
def select[self, choice_index: int] -> None:
if choice_index not in range[1, len[self.RECIPES] + 1]:
print["That selection does not exist"]
return
product = self.RECIPES[choice_index - 1]
if self.cash_box.has_credit_for[product.price]:
product.make[]
self.cash_box.deduct[product.price]
self.cash_box.return_coins[]
else:
print["Sorry. Not enough money deposited."]
def main[] -> None:
m = CoffeeMachine[]
while m.one_action[]:
pass
print[f"Total credit: ${m.cash_box.credit / 100:.2f}"]
if __name__ == "__main__":
main[]
0 hợp lý - tại sao không gọi nó thay vì viếtprint["Returning {0} cents.".format[self.cashBox.haveYou]]
Chuyển bản thân của một đối tượng khác cho phương pháp
from typing import NamedTuple
class CashBox:
def __init__[self] -> None:
self.credit = 0
def deposit[self, amount: int] -> None:
self.credit += amount
print[f"Depositing {amount} cents. You have {self.credit} cents credit."]
def return_coins[self] -> None:
print[f"Returning {self.credit / 100} dollars."]
self.credit = 0
def has_credit_for[self, price: int] -> bool:
return self.credit >= price
def deduct[self, amount: int] -> None:
self.credit -= amount
class Product[NamedTuple]:
name: str
price: int
recipe: list[str]
def make[self]:
for item in self.recipe:
print["dispensing", item]
print["Enjoy your", self.name]
class CoffeeMachine:
RECIPES = [
Product[*args]
for i, args in enumerate[
[
["Black coffee", 35, ["cup", "coffee", "water"]],
["White coffee", 35, ["cup", "coffee", "creamer", "water"]],
["Sweet coffee", 35, ["cup", "coffee", "sugar", "water"]],
["White & Sweet coffee", 35, ["cup", "coffee", "sugar", "creamer", "water"]],
["Bouillon", 25, ["cup bouillonPowder", "water"]],
], 1
]
]
def __init__[self] -> None:
self.cash_box = CashBox[]
def one_action[self] -> bool:
command = input["""
______________________________________________________
PRODUCT LIST: all 35 cents, except bouillon [25 cents]
1=black, 2=white, 3=sweet, 4=sweet & white, 5=bouillon
Sample Commands: insert 25, select 1, cancel, quit.
Your command:
"""]
words = command.lower[].split[]
if 'select' in words:
self.select[int[words[1]]]
elif 'insert' in words:
amount = int[words[1]]
coins_allowed = {5, 10, 25, 50}
if amount in coins_allowed:
self.cash_box.deposit[amount]
else:
print["We only take half-dollars, quarters, dimes, and nickels."]
elif 'cancel' in words:
print["Cancelling transaction. Returning to main menu: "]
self.cash_box.return_coins[]
elif 'quit' in words:
return False
else:
print["Invalid command."]
return True
def select[self, choice_index: int] -> None:
if choice_index not in range[1, len[self.RECIPES] + 1]:
print["That selection does not exist"]
return
product = self.RECIPES[choice_index - 1]
if self.cash_box.has_credit_for[product.price]:
product.make[]
self.cash_box.deduct[product.price]
self.cash_box.return_coins[]
else:
print["Sorry. Not enough money deposited."]
def main[] -> None:
m = CoffeeMachine[]
while m.one_action[]:
pass
print[f"Total credit: ${m.cash_box.credit / 100:.2f}"]
if __name__ == "__main__":
main[]
1 không giới hạn giống như thay thế đèn pha của bạn bằng những con lươn giận dữ. Đó là sáng tạo, nhưng hoàn toàn khủng khiếp. Đừng làm điều này.from typing import NamedTuple
class CashBox:
def __init__[self] -> None:
self.credit = 0
def deposit[self, amount: int] -> None:
self.credit += amount
print[f"Depositing {amount} cents. You have {self.credit} cents credit."]
def return_coins[self] -> None:
print[f"Returning {self.credit / 100} dollars."]
self.credit = 0
def has_credit_for[self, price: int] -> bool:
return self.credit >= price
def deduct[self, amount: int] -> None:
self.credit -= amount
class Product[NamedTuple]:
name: str
price: int
recipe: list[str]
def make[self]:
for item in self.recipe:
print["dispensing", item]
print["Enjoy your", self.name]
class CoffeeMachine:
RECIPES = [
Product[*args]
for i, args in enumerate[
[
["Black coffee", 35, ["cup", "coffee", "water"]],
["White coffee", 35, ["cup", "coffee", "creamer", "water"]],
["Sweet coffee", 35, ["cup", "coffee", "sugar", "water"]],
["White & Sweet coffee", 35, ["cup", "coffee", "sugar", "creamer", "water"]],
["Bouillon", 25, ["cup bouillonPowder", "water"]],
], 1
]
]
def __init__[self] -> None:
self.cash_box = CashBox[]
def one_action[self] -> bool:
command = input["""
______________________________________________________
PRODUCT LIST: all 35 cents, except bouillon [25 cents]
1=black, 2=white, 3=sweet, 4=sweet & white, 5=bouillon
Sample Commands: insert 25, select 1, cancel, quit.
Your command:
"""]
words = command.lower[].split[]
if 'select' in words:
self.select[int[words[1]]]
elif 'insert' in words:
amount = int[words[1]]
coins_allowed = {5, 10, 25, 50}
if amount in coins_allowed:
self.cash_box.deposit[amount]
else:
print["We only take half-dollars, quarters, dimes, and nickels."]
elif 'cancel' in words:
print["Cancelling transaction. Returning to main menu: "]
self.cash_box.return_coins[]
elif 'quit' in words:
return False
else:
print["Invalid command."]
return True
def select[self, choice_index: int] -> None:
if choice_index not in range[1, len[self.RECIPES] + 1]:
print["That selection does not exist"]
return
product = self.RECIPES[choice_index - 1]
if self.cash_box.has_credit_for[product.price]:
product.make[]
self.cash_box.deduct[product.price]
self.cash_box.return_coins[]
else:
print["Sorry. Not enough money deposited."]
def main[] -> None:
m = CoffeeMachine[]
while m.one_action[]:
pass
print[f"Total credit: ${m.cash_box.credit / 100:.2f}"]
if __name__ == "__main__":
main[]
2 là một lời nói dối hoàn toàn, vì nó lặp lại cho đến khi người dùng bỏ việc. Loại bỏ vòng lặp của bạn trong chức năng đó và giữ vòng lặp của bạn ở cấp độ bên ngoài.Đừng
from typing import NamedTuple
class CashBox:
def __init__[self] -> None:
self.credit = 0
def deposit[self, amount: int] -> None:
self.credit += amount
print[f"Depositing {amount} cents. You have {self.credit} cents credit."]
def return_coins[self] -> None:
print[f"Returning {self.credit / 100} dollars."]
self.credit = 0
def has_credit_for[self, price: int] -> bool:
return self.credit >= price
def deduct[self, amount: int] -> None:
self.credit -= amount
class Product[NamedTuple]:
name: str
price: int
recipe: list[str]
def make[self]:
for item in self.recipe:
print["dispensing", item]
print["Enjoy your", self.name]
class CoffeeMachine:
RECIPES = [
Product[*args]
for i, args in enumerate[
[
["Black coffee", 35, ["cup", "coffee", "water"]],
["White coffee", 35, ["cup", "coffee", "creamer", "water"]],
["Sweet coffee", 35, ["cup", "coffee", "sugar", "water"]],
["White & Sweet coffee", 35, ["cup", "coffee", "sugar", "creamer", "water"]],
["Bouillon", 25, ["cup bouillonPowder", "water"]],
], 1
]
]
def __init__[self] -> None:
self.cash_box = CashBox[]
def one_action[self] -> bool:
command = input["""
______________________________________________________
PRODUCT LIST: all 35 cents, except bouillon [25 cents]
1=black, 2=white, 3=sweet, 4=sweet & white, 5=bouillon
Sample Commands: insert 25, select 1, cancel, quit.
Your command:
"""]
words = command.lower[].split[]
if 'select' in words:
self.select[int[words[1]]]
elif 'insert' in words:
amount = int[words[1]]
coins_allowed = {5, 10, 25, 50}
if amount in coins_allowed:
self.cash_box.deposit[amount]
else:
print["We only take half-dollars, quarters, dimes, and nickels."]
elif 'cancel' in words:
print["Cancelling transaction. Returning to main menu: "]
self.cash_box.return_coins[]
elif 'quit' in words:
return False
else:
print["Invalid command."]
return True
def select[self, choice_index: int] -> None:
if choice_index not in range[1, len[self.RECIPES] + 1]:
print["That selection does not exist"]
return
product = self.RECIPES[choice_index - 1]
if self.cash_box.has_credit_for[product.price]:
product.make[]
self.cash_box.deduct[product.price]
self.cash_box.return_coins[]
else:
print["Sorry. Not enough money deposited."]
def main[] -> None:
m = CoffeeMachine[]
while m.one_action[]:
pass
print[f"Total credit: ${m.cash_box.credit / 100:.2f}"]
if __name__ == "__main__":
main[]
3 - Sử dụng from typing import NamedTuple
class CashBox:
def __init__[self] -> None:
self.credit = 0
def deposit[self, amount: int] -> None:
self.credit += amount
print[f"Depositing {amount} cents. You have {self.credit} cents credit."]
def return_coins[self] -> None:
print[f"Returning {self.credit / 100} dollars."]
self.credit = 0
def has_credit_for[self, price: int] -> bool:
return self.credit >= price
def deduct[self, amount: int] -> None:
self.credit -= amount
class Product[NamedTuple]:
name: str
price: int
recipe: list[str]
def make[self]:
for item in self.recipe:
print["dispensing", item]
print["Enjoy your", self.name]
class CoffeeMachine:
RECIPES = [
Product[*args]
for i, args in enumerate[
[
["Black coffee", 35, ["cup", "coffee", "water"]],
["White coffee", 35, ["cup", "coffee", "creamer", "water"]],
["Sweet coffee", 35, ["cup", "coffee", "sugar", "water"]],
["White & Sweet coffee", 35, ["cup", "coffee", "sugar", "creamer", "water"]],
["Bouillon", 25, ["cup bouillonPowder", "water"]],
], 1
]
]
def __init__[self] -> None:
self.cash_box = CashBox[]
def one_action[self] -> bool:
command = input["""
______________________________________________________
PRODUCT LIST: all 35 cents, except bouillon [25 cents]
1=black, 2=white, 3=sweet, 4=sweet & white, 5=bouillon
Sample Commands: insert 25, select 1, cancel, quit.
Your command:
"""]
words = command.lower[].split[]
if 'select' in words:
self.select[int[words[1]]]
elif 'insert' in words:
amount = int[words[1]]
coins_allowed = {5, 10, 25, 50}
if amount in coins_allowed:
self.cash_box.deposit[amount]
else:
print["We only take half-dollars, quarters, dimes, and nickels."]
elif 'cancel' in words:
print["Cancelling transaction. Returning to main menu: "]
self.cash_box.return_coins[]
elif 'quit' in words:
return False
else:
print["Invalid command."]
return True
def select[self, choice_index: int] -> None:
if choice_index not in range[1, len[self.RECIPES] + 1]:
print["That selection does not exist"]
return
product = self.RECIPES[choice_index - 1]
if self.cash_box.has_credit_for[product.price]:
product.make[]
self.cash_box.deduct[product.price]
self.cash_box.return_coins[]
else:
print["Sorry. Not enough money deposited."]
def main[] -> None:
m = CoffeeMachine[]
while m.one_action[]:
pass
print[f"Total credit: ${m.cash_box.credit / 100:.2f}"]
if __name__ == "__main__":
main[]
4, vì bạn không bao giờ muốn cho phép from typing import NamedTuple
class CashBox:
def __init__[self] -> None:
self.credit = 0
def deposit[self, amount: int] -> None:
self.credit += amount
print[f"Depositing {amount} cents. You have {self.credit} cents credit."]
def return_coins[self] -> None:
print[f"Returning {self.credit / 100} dollars."]
self.credit = 0
def has_credit_for[self, price: int] -> bool:
return self.credit >= price
def deduct[self, amount: int] -> None:
self.credit -= amount
class Product[NamedTuple]:
name: str
price: int
recipe: list[str]
def make[self]:
for item in self.recipe:
print["dispensing", item]
print["Enjoy your", self.name]
class CoffeeMachine:
RECIPES = [
Product[*args]
for i, args in enumerate[
[
["Black coffee", 35, ["cup", "coffee", "water"]],
["White coffee", 35, ["cup", "coffee", "creamer", "water"]],
["Sweet coffee", 35, ["cup", "coffee", "sugar", "water"]],
["White & Sweet coffee", 35, ["cup", "coffee", "sugar", "creamer", "water"]],
["Bouillon", 25, ["cup bouillonPowder", "water"]],
], 1
]
]
def __init__[self] -> None:
self.cash_box = CashBox[]
def one_action[self] -> bool:
command = input["""
______________________________________________________
PRODUCT LIST: all 35 cents, except bouillon [25 cents]
1=black, 2=white, 3=sweet, 4=sweet & white, 5=bouillon
Sample Commands: insert 25, select 1, cancel, quit.
Your command:
"""]
words = command.lower[].split[]
if 'select' in words:
self.select[int[words[1]]]
elif 'insert' in words:
amount = int[words[1]]
coins_allowed = {5, 10, 25, 50}
if amount in coins_allowed:
self.cash_box.deposit[amount]
else:
print["We only take half-dollars, quarters, dimes, and nickels."]
elif 'cancel' in words:
print["Cancelling transaction. Returning to main menu: "]
self.cash_box.return_coins[]
elif 'quit' in words:
return False
else:
print["Invalid command."]
return True
def select[self, choice_index: int] -> None:
if choice_index not in range[1, len[self.RECIPES] + 1]:
print["That selection does not exist"]
return
product = self.RECIPES[choice_index - 1]
if self.cash_box.has_credit_for[product.price]:
product.make[]
self.cash_box.deduct[product.price]
self.cash_box.return_coins[]
else:
print["Sorry. Not enough money deposited."]
def main[] -> None:
m = CoffeeMachine[]
while m.one_action[]:
pass
print[f"Total credit: ${m.cash_box.credit / 100:.2f}"]
if __name__ == "__main__":
main[]
5 mặc định.Có những vấn đề khác, nhưng đây là một khởi đầu:
Đề xuất
from typing import NamedTuple
class CashBox:
def __init__[self] -> None:
self.credit = 0
def deposit[self, amount: int] -> None:
self.credit += amount
print[f"Depositing {amount} cents. You have {self.credit} cents credit."]
def return_coins[self] -> None:
print[f"Returning {self.credit / 100} dollars."]
self.credit = 0
def has_credit_for[self, price: int] -> bool:
return self.credit >= price
def deduct[self, amount: int] -> None:
self.credit -= amount
class Product[NamedTuple]:
name: str
price: int
recipe: list[str]
def make[self]:
for item in self.recipe:
print["dispensing", item]
print["Enjoy your", self.name]
class CoffeeMachine:
RECIPES = [
Product[*args]
for i, args in enumerate[
[
["Black coffee", 35, ["cup", "coffee", "water"]],
["White coffee", 35, ["cup", "coffee", "creamer", "water"]],
["Sweet coffee", 35, ["cup", "coffee", "sugar", "water"]],
["White & Sweet coffee", 35, ["cup", "coffee", "sugar", "creamer", "water"]],
["Bouillon", 25, ["cup bouillonPowder", "water"]],
], 1
]
]
def __init__[self] -> None:
self.cash_box = CashBox[]
def one_action[self] -> bool:
command = input["""
______________________________________________________
PRODUCT LIST: all 35 cents, except bouillon [25 cents]
1=black, 2=white, 3=sweet, 4=sweet & white, 5=bouillon
Sample Commands: insert 25, select 1, cancel, quit.
Your command:
"""]
words = command.lower[].split[]
if 'select' in words:
self.select[int[words[1]]]
elif 'insert' in words:
amount = int[words[1]]
coins_allowed = {5, 10, 25, 50}
if amount in coins_allowed:
self.cash_box.deposit[amount]
else:
print["We only take half-dollars, quarters, dimes, and nickels."]
elif 'cancel' in words:
print["Cancelling transaction. Returning to main menu: "]
self.cash_box.return_coins[]
elif 'quit' in words:
return False
else:
print["Invalid command."]
return True
def select[self, choice_index: int] -> None:
if choice_index not in range[1, len[self.RECIPES] + 1]:
print["That selection does not exist"]
return
product = self.RECIPES[choice_index - 1]
if self.cash_box.has_credit_for[product.price]:
product.make[]
self.cash_box.deduct[product.price]
self.cash_box.return_coins[]
else:
print["Sorry. Not enough money deposited."]
def main[] -> None:
m = CoffeeMachine[]
while m.one_action[]:
pass
print[f"Total credit: ${m.cash_box.credit / 100:.2f}"]
if __name__ == "__main__":
main[]