我目前正在参加在线python课程,并且类和方法有问题。我的老师希望我使用“ addlevels”方法打印出原始强度点+“ addlevels”方法中的点。
我试图将return放到该方法中,但这没有用。我也尝试过使用Hero.strengthsPt Transactions和print(str(Hero.strengthPtwego)),但是也没有用。使用str(Hero.strengthPts)时,它只会打印出90点,而不是增加10点。
class Superhero:
def __init__(self, name = "", strengthPts = 1):
self.name = name
self.strengthPts = strengthPts
def addlevels(self, points = 10):
strengthPtsAdded = self.strengthPts + points
def main():
Hero = Superhero("Falcon", 90,)
print("Name: " + Hero.name)
print("Level: " + str(Hero.strengthPts))
Hero.addlevels()
print("Heroes level after training " + str(Hero.strengthPts) + " .")
main()
我希望代码输出Falcon的名称,原始强度点将为90,然后添加后的强度点应为100。结果是该代码确实打印了名称“ Falcon”,原始强度点,但最后一行打印“训练后的英雄等级:90,而不是100。
答案 0 :(得分:1)
如何添加新的strengthPts_modified变量,以便在以后要使用它时保留原始的strengthPts。
class Superhero:
def __init__(self, name = "", strengthPts = 1):
self.name = name
self.strengthPts = strengthPts
self.strengthPts_modified=self.strengthPts
def addlevels(self, points = 10):
self.strengthPts_modified += points
def main():
Hero = Superhero("Falcon", 90,)
print("Name: " + Hero.name)
print("Level: " + str(Hero.strengthPts))
Hero.addlevels()
Hero.addlevels()
print("Heroes level after training " + str(Hero.strengthPts_modified) + " .")
main()