SyntaxError: 创建类[closed]实例时语法无效。

问题描述 投票:2回答:1

我在Python shell 3.3.2中运行这段代码,但它给我的是 SyntaxError: invalid syntax.

class Animal(object):
    """Makes cute animals."""
    is_alive = True
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def description(self):
        print (self.name)
        print (self.age)

hippo = Animal("2312",21)#error occurs in that line
hippo.description()

我是一个Python新手,我不知道如何修复这段代码。

Screenshot from IDLE

python syntax python-idle
1个回答
3
投票

你没有正确地缩进你的代码。你的方法的主体是正确缩进的,但是你忘了缩进 doc 字符串,而你也忘了缩进 def 语句,此外还有 is_alive = True 语句。如果你在IDLE中像这样输入,就可以了。

>>> class Animal(object):
...     """Makes cute animals."""
...     is_alive = True
...     def __init__(self, name, age):
...         self.name = name
...         self.age = age
...     def description(self):
...         print(self.name)
...         print(self.age)
...
>>> hippo = Animal("2312", 21)
>>> hippo.description()
2312
21

块语句的主体是指发生在 :例如,如果你输入这样的内容:

if 'a' == 'b':
    print('This will never print')
else:
    print('Of course a is not equal to b!')

如果你这样输入

if 'a' == 'b':
print('This will never print')
else:
print('Of course a is not equal to b!')

这不是有效的Python语法

© www.soinside.com 2019 - 2024. All rights reserved.