python - Python - 将函数值转换为 int 或 float 以进行比较
问题描述
所以本质上,我正在模拟一个钱箱,我在其中接收硬币并建立用户信用,然后当用户请求购买物品时,我检查以确保他们有足够的信用来购买该物品。
我遇到的问题是,当我使用 haveYou 函数时,我尝试比较两个值 price 和 credit 在当前版本的代码中,self.price 在 CashBox 中设置为 35。init,以便 Selector.select() 中的 if 语句正常工作。
如果我在 init 函数中包含 self.price = 0,它会保持该值并表示信用和价格相等,因此如果我尝试返回 self.credit >= self.price,它会继续,引用 getPrice 方法的返回,它说我无法将 int 与函数值进行比较。我已经检查过了,这绝对是 self.price 的问题。
所以我的问题是,如何将函数值转换为 int,或者将 getPrice 的返回值设置为 int 开头?我已经看过了,但是互联网上充满了 int 以浮动到字符串的东西,我找不到任何关于这个的东西。我在这个桌子上敲了大约 5 个小时的头,非常感谢您的帮助。谢谢
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(self.credit)
print(type(self.credit))
return self.credit
def returnCoins(self):
print("Returning ", self.credit/100, " dollars.")
self.totalReceived = 0
def haveYou(self,amount):
price = Product.getPrice
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("""
That is not one of the allowed coins,
please insert a penny, nickel, dime, quarter,
or half-dollar. Thank you.
""")
elif 'cancel' in words:
print("Cancelling transaction. Returning to main menu: ")
self.cashBox.returnCoins()
elif 'quit' in words:
print("Have a nice day!")
break
else:
print("That is not an option")
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):
if self.cashBox.haveYou(self.credit) == True:
self.choiceIndex = choiceIndex
self.recipe = recipes.get(choiceIndex)
#print(self.recipe,"Great selection")
product = Product(*self.recipe)
price = CashBox.haveYou(*self.recipe)
product.make()
else:
print("You don't have enough credit for that, please insert more money.")
else:
print("That selection does not exist")
def main():
m = CoffeeMachine()
while m.oneAction():
pass
total = m.totalCash()
print(f"Total Cash: ${total/100:.2f}")
if __name__ == "__main__":
取决于我正在尝试:取消注释 self.price = 35
Exception has occurred: AttributeError
'int' object has no attribute 'price'
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 81, in getPrice
return self.price
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 22, in haveYou
price = Product.getPrice(self.price) + self.price
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 108, in select
if self.cashBox.haveYou(self.credit) == True:
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 50, in oneAction
Selector.select(self,int(words[1]))
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 122, in main
while m.oneAction():
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 128, in <module>
main()
或者如果在 hasYou 我使用
price = Product.getPrice
return self.credit >= price
Exception has occurred: TypeError
'>=' not supported between instances of 'int' and 'function'
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 23, in haveYou
return self.credit >= price
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 108, in select
if self.cashBox.haveYou(self.credit) == True:
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 50, in oneAction
Selector.select(self,int(words[1]))
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 122, in main
while m.oneAction():
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 128, in <module>
main()
解决方案
您需要()
在最后添加才能真正获得价值。
所以而不是:
price = Product.getPrice
return self.credit >= price
利用:
price = Product(<Here put the 3 values that this class needs>).getPrice()
return self.credit >= price
推荐阅读
- kubernetes - 使用 EnvoyProxy 添加本地速率限制
- loops - VHDL 中等待、无限循环、while 循环和 for 循环语句的综合
- r - Geom_point 和 ggboxplot 以及 ggpair 在 ggplot 中错误地匹配了所有绘图点
- python - 通过 python 请求上传图像时出现错误 400(错误请求)
- swift - 如何解决每 14 天在设备上发生的间歇性崩溃?
- mysql - IntegerField 不接受负数 django
- python - 如何为并发请求分析我的 API?
- python - 在在线 Jupyter Notebook 上打开 .csv
- python - Pandas 解析文本数据并根据条件对齐列
- javascript - 从表格单元格值动态生成 img src