Python-将函数值转换为int或float进行比较

Python-将函数值转换为int或float进行比较,python,Python,所以本质上,我是在模拟一个现金箱,在那里我接收硬币并建立用户信用,然后当用户请求购买某个项目时,我检查以确保他们对该项目有足够的信用 我遇到的问题是,当我使用haveYou函数时,我会尝试比较price和credit这两个值 在当前版本的代码中,self.price只是在CashBox中设置为35。init,因此Selector.select()中的if语句可以正常工作 如果我在init函数中包含self.price=0,它将保持该值,并表示信用和价格相等,因此它将继续 如果我尝试返回self.

所以本质上,我是在模拟一个现金箱,在那里我接收硬币并建立用户信用,然后当用户请求购买某个项目时,我检查以确保他们对该项目有足够的信用

我遇到的问题是,当我使用haveYou函数时,我会尝试比较price和credit这两个值 在当前版本的代码中,self.price只是在CashBox中设置为35。init,因此Selector.select()中的if语句可以正常工作

如果我在init函数中包含self.price=0,它将保持该值,并表示信用和价格相等,因此它将继续 如果我尝试返回self.credit>=self.price,引用getPrice方法的返回,它会说我无法将int与函数值进行比较。我已经检查过了,这肯定是自定价的问题

所以我的问题是,如何将函数值转换为int,或者首先将getPrice的返回设置为int?我已经看过了,但是互联网上充斥着int到string的东西,我找不到任何关于这个的东西。 这一次,我的头撞在桌子上大约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()
发生异常:TypeError “>=”在“int”和“function”的实例之间不受支持 文件“C:\Users\Tanner-Harmer\Desktop\Coffee2\CashBox.py”,第23行,在haveYou中 返回self.credit>=价格 文件“C:\Users\Tanner-Harmer\Desktop\Coffee2\CashBox.py”,第108行,选择 如果self.cashBox.haveYou(self.credit)=True: 文件“C:\Users\Tanner-Harmer\Desktop\Coffee2\CashBox.py”,第50行,在oneAction中 Selector.select(self,int(单词[1])) 文件“C:\Users\Tanner-Harmer\Desktop\Coffee2\CashBox.py”,第122行,主目录 而m.oneAction(): 文件“C:\Users\Tanner-Harmer\Desktop\Coffee2\CashBox.py”,第128行,在 main() 您需要在末尾添加
()
,以实际获取值

因此,不是:

price = Product.getPrice  
return self.credit >= price
使用:

price=Product().getPrice()
返回self.credit>=价格
如果精确性是关键(在金融领域经常如此),则永远不要使用浮点数。相反,我建议您将货币存储为以便士为单位的整数

例如,如果某人的银行账户余额为1343.98美元,那么您将其存储为134398便士。无论何时将对象强制转换为字符串,它都会得到一个很好的小数点

import math

class PecuniaryPurse:
    currency_codes = frozenset((
        "EUR", "USD", "GBP", "JPY", "CHF",
        "AUD", "CAD"
    ))

    @classmethod
    def to_int(cls, amount):
        if isinstance(amount, cls):
            _amount_int = amount._amount
        else:
            _amount_flt = float(str(amount))
            _amount_int = int(amount)
            if not math.isclose(amount, _amount_flt):
                raise ValueError()
        return _amount_int

    def __init__(self, currency_code, _amount = 0):
        try:
            assert (currency_code in self.currency_codes)
            self._currency_code = currency_code
            self._amount = type(self).to_int(_amount)
        finally:
            pass

    def __str__(self):
        return ''.join(str(x) for x in (
                self._currency_code,
                "  ",
                str(self._amount // 100),
                ".",
                str(self._amount % 100)
        ))

    def __add__(self, other):
        if isinstance(other, type(self)):
            assert(self._currency_code == other._currency_code)
            return type(self)(self._currency_code, self._amount + other._amount)
        else:
            other = type(self).to_int(other)
        return type(self)(self._currency_code, self._amount + other)

PP = PecuniaryPurse
p = PP("USD", 1234) + PP("USD", 99)
print(p) # USD  13.33

我试过了,但是getPrice()缺少1个必需的位置参数:“self”,或者如果我将self放入其中:“CashBox”对象没有属性“price”,我会在CashBox中包含它,而不会覆盖新参数value@T_lastname看见now@T_lastname这三个值应该是名称、价格和价格。谢谢你,我不得不多走几步,但你让我做到了。非常感谢你。我会将结果发布给任何需要了解我如何解决问题的人it@T_lastname乐于帮助:-)这里有太多的代码,无法真正解决问题,而且也不清楚您要做什么。例如,你能用自己的话解释一下,你希望通过像
self.credit=CashBox.\uuu init\uuuu
这样的行来完成什么吗?这是一个相对复杂的尝试,这可能不是你想要的。这非常有趣,我会尝试以某种方式合并它。准确并不一定重要,但就学习而言,这里有些东西我以前没见过,所以谢谢你
price = Product.getPrice  
return self.credit >= price
price = Product(<Here put the 3 values that this class needs>).getPrice()  
return self.credit >= price
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,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("""
                    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):
            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()              
            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__":
    main()
import math

class PecuniaryPurse:
    currency_codes = frozenset((
        "EUR", "USD", "GBP", "JPY", "CHF",
        "AUD", "CAD"
    ))

    @classmethod
    def to_int(cls, amount):
        if isinstance(amount, cls):
            _amount_int = amount._amount
        else:
            _amount_flt = float(str(amount))
            _amount_int = int(amount)
            if not math.isclose(amount, _amount_flt):
                raise ValueError()
        return _amount_int

    def __init__(self, currency_code, _amount = 0):
        try:
            assert (currency_code in self.currency_codes)
            self._currency_code = currency_code
            self._amount = type(self).to_int(_amount)
        finally:
            pass

    def __str__(self):
        return ''.join(str(x) for x in (
                self._currency_code,
                "  ",
                str(self._amount // 100),
                ".",
                str(self._amount % 100)
        ))

    def __add__(self, other):
        if isinstance(other, type(self)):
            assert(self._currency_code == other._currency_code)
            return type(self)(self._currency_code, self._amount + other._amount)
        else:
            other = type(self).to_int(other)
        return type(self)(self._currency_code, self._amount + other)

PP = PecuniaryPurse
p = PP("USD", 1234) + PP("USD", 99)
print(p) # USD  13.33