Python如果小于某个数,如何替换布尔值?

2024-10-04 05:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建自己的对象和类,并且正在尝试编写一个方法,该方法将检查对象中的一个数字,如果发现该数字小于50,它将替换另一个预定义值为False的对象的布尔值。你知道吗

目前我有一个if/else语句,检查gamePrice的值是否小于50,如果小于50,它应该将isASteal的值改为True。如果大于50,则应更改为False。isASteal的默认值设置为False,gamePrice的默认值为0

class videoGames(object):
def __init__(self, gameName = '', gamePrice = 0, isASteal = False):
    self.gameName = gameName
    self.gamePrice = gamePrice
    self.isASteal = isASteal

def gameValue(self):
    if self.gamePrice == 0 or self.gamePrice >= 50:
        self.isASteal = False

    else:
        self.isASteal = True
    fullGames = 'Title:{}\t\ Price: ${}\t\ Steal: {}'.format(self.gameName, self.gamePrice, self.isASteal)

    return fullGames

如果用户调用函数时说:

    game1 = videoGames('Call of Duty', 15)

他们应该得到如下输出:

     Title: Call of Duty      Price: $15           Steal: True

相反,我得到:

     Title: Call of Duty       Price: $15          Steal: False

Tags: of对象方法selffalsetruetitle数字
1条回答
网友
1楼 · 发布于 2024-10-04 05:25:42

如果要在调用实例时打印字符串,可以重写类的dunder__str__()方法

class videoGames(object):
    def __init__(self, gameName = '', gamePrice = 0, isASteal = False):
        self.gameName = gameName
        self.gamePrice = gamePrice
        self.isASteal = isASteal

    #Overriden ___str__ method
    def __str__(self):
        if self.gamePrice == 0 or self.gamePrice >= 50:
            self.isASteal = False

        else:
            self.isASteal = True
        fullGames = 'Title:{}\t\ Price: ${}\t\ Steal: {}'.format(self.gameName, self.gamePrice, self.isASteal)

        return fullGames

game1 = videoGames('Call of Duty', 15)
print(game1)

输出将是

Title:Call of Duty   Price: $15  Steal: True

相关问题 更多 >