首页 > 解决方案 > 字符串试图引用实例的属性错误

问题描述

我收到此错误 AttributeError: 'str' object has no attribute 'health' ,我认为这是因为我尝试修改的对象是实例的属性,但是当我引用该实例时,我得到将其更改为字符串的用户输入。如何更改它以使字符串引用实例?我在这里看过一篇文章,但它是 5 年前的,它似乎已经过时并且没有帮助。

所以在终端它显示

Heal who? Rachel # I entered the Rachel part

这是来自这部分代码

heal = input("Heal who? ")
Sidekick.heal(heal)

它执行

    def heal(self,target):
        """Heals the target by 20 hp."""
        if self.level <= 5:
            restore = 20
        elif self.level <= 10:
            restore = 35
        elif self.level <= 15:
            restore = 50
        target.health += restore
        if target.health > target.full_health:
            restore = target.full_health - target.health
            target.health = target.full_health
        print("Healed " + target.name + " by " + str(restore) + " hp.")

标签: python

解决方案


推荐阅读