【问题标题】:Python - How to replace boolean value if less than a certain number?Python - 如果小于某个数字,如何替换布尔值?
【发布时间】:2019-10-08 04:23:19
【问题描述】:

致力于创建我自己的对象和类,并尝试编写一种方法来检查对象中的数字,如果发现小于 50,它将替换另一个具有预定义的对象的布尔值False 的定义值。

目前我有一个 if/else 语句来检查 gamePrice 的值是否小于 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

【问题讨论】:

  • 我运行了你的代码并得到了正确的答案,你能再检查一下问题吗
  • 您不应该在不在方法中的类中有代码。请检查您的缩进。
  • @DeveshKumarSingh 它不起作用
  • 你在做print(game1.gameValue()) 吗?我得到输出Title:Call of Duty \ Price: $15 \ Steal: True
  • 不,我正在打印(game1)

标签: python python-3.x object boolean operators


【解决方案1】:

如果要在调用实例时打印字符串,可以重写该类的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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 2022-08-16
    • 2012-10-13
    • 2016-04-24
    • 2015-08-28
    • 2019-04-12
    • 1970-01-01
    相关资源
    最近更新 更多