python冒号错误语法无效

2024-10-01 22:37:46 发布

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

class Personaje:
    def__init__(self,name):
        self.name=pepe
        self.type=warrior
        self.health=100
        def eat(self,food):
            if(food=="manzana"):
                self.health-=10
            elif(food=="leche"):
                self.health+=5
            else(food=="mondongo"):
                self.health+= int(0.0001) 

我得到无效的语法在(自身名称):<;<; 在


Tags: nameltselfiffoodinitdeftype
1条回答
网友
1楼 · 发布于 2024-10-01 22:37:46

问题1

看看错误:

  File "<ipython-input-4-3873e72b95ad>", line 3
    def__init__(self,name):
                          ^
SyntaxError: invalid syntax

def__init__之间应该有一个空格,因此__init__函数的定义应该是:

^{pr2}$

问题2

else语句不采用if或{}do之类的表达式,因此会导致以下语法错误:

  File "<ipython-input-5-661f08a520ce>", line 12
    else(food=="mondongo"):
        ^
SyntaxError: invalid syntax

else表示其他所有内容,因此如果您希望它只适用于“mondongo”,则应该在那里使用另一个elif。在

问题3

函数eat__init__函数内定义,导致:

<ipython-input-22-9789ced9c556> in <module>()
  > 1 p.eat('leche')

AttributeError: Personaje instance has no attribute 'eat'

如果取消插入函数(向左移动4个空格),则eat将在类中定义,而不是在init函数中定义。所以基本结构应该这样缩进:

class Personaje:
    def __init__(...):
        pass
    def eat(...):
        pass

问题4

未将Personaje名称设置为__init__函数中指定的名称。如果您希望默认名称为pepe,并键入warrior,我建议您将init函数改为如下所示:

def __init__(self, name="pepe", type="warrior"):
    self.name = name
    self.type = type
    self.health = 100

您的最后一个Personaje类现在应该如下所示:

class Personaje:

    def __init__(self, name="pepe",type="warrior"):
        self.name = name
        self.type = type
        self.health = 100

    def eat(self, food):
        if(food=="manzana"):
            self.health -= 10
        elif(food=="leche"):
            self.health += 5
        else:
            self.health += int(0.0001)

相关问题 更多 >

    热门问题