在 class 函数中使用 "if" 语句升级 Player class 实例

Using an "if" statement in a class function to level-up Player class instance

我正在为基于文本的 Python 游戏中的 Player(用户)创建 class。级别在Playerclass中表示为级别函数。当用户成功完成任务时,我包含了一个 level_up() 函数。

完成任务应该会提高用户的等级,return用户的新等级。但是我运行程序的时候,等级并没有加1,函数return用户的等级也没有。

感谢任何反馈、意见和建议。

class Player(object):
    def __init__(self, name:str, health:int, level:int, strength:int, quest):
        self.name = name
        self.health = health
        self.level = level
        self.strength = strength
        self.quest = False

    def __str__(self):
        return "%s stats:\n HP %s\n Level %s\n Strength %s" % (self.name, self.health, self.level, self.strength)

    def level_up(self):
        if self.quest is True:
            self.level += 1
            return "You have leveled up. You are level %s! Congratulations." % (self.level)
        else:
            pass


user = Player('User_name', 1, 1, 1, False)
print(user)

user.quest = True

user.level_up()

你 return "you have leveled up" 字符串但你从不打印它。您必须打印它才能看到它:

def level_up(self):
    if self.quest is True:
        self.level += 1
        print("You have leveled up. You are level %s! Congratulations." % (self.level))

或者

# Only do this if level_up returns a string instead of printing one
print(user.level_up())