类型错误:未绑定方法fight()必须使用Pokemon实例作为第一个参数进行调用(得到类型实例,而非一个实例)

2024-04-24 22:23:25 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

# pokemon1
class Pokemon(object):
    def __init__(self,name,hp,damage):
        self.name = name     
        self.hp = hp        
        self.damage = damage 

    def fight(self,other):
        if(self.hp > 0):
            print("%s did %d damage to %s"%(self.name,self.damage,other.name))
            other.hp -= self.damage
            if (other.hp > 0):
                print("%s has %d hp left" % (other.name, other.hp))
            else:
                print("%s has died" % (other.name))
            return other.fight(self)
        else:
            print("%s wins! (%d hp left)"%(other.name,other.hp))
            return other,self  

class pikachu(Pokemon):
    def __init__(self):
        super(pikachu, self).__init__('pikachu', 100, 10)

class pidgy(Pokemon):
    def __init__(self):
        super(pidgy, self).__init__('pidgy', 200, 12)

#main
import pokemon1

pikachu = pokemon1.pikachu
pidgy = pokemon1.pidgy

p = pokemon1.Pokemon
p.fight(pikachu,pidgy)

Tags: nameselfifinitdefclasshpother
2条回答

Reinderien是对的,但我尝试了您的代码,发现了一个不同的问题,您设计的类与您尝试使用它的方式不同。你知道吗

此代码应该起作用:

pikachu = pokemon1.pikachu
pidgy = pokemon1.pidgy

pikachu.fight(pidgy)

您需要在最后一行中调用Pokemon(),而不是Pokemon来调用构造函数。你知道吗

相关问题 更多 >