致力于创建自己的对象和类,并尝试编写一种方法来检查对象中的数字,如果发现该数字小于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
答案 0 :(得分: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