python - 语法错误 : invalid syntax when creating a instance of class

标签 python syntax python-idle

<分区>

我在 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

最佳答案

您没有正确缩进代码。您的方法主体缩进正确,但除了 is_alive = True 语句外,您还忘记缩进文档字符串和方法的 def 语句。如果你像这样在 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

block 语句的主体是 : 之后的任何内容,并且需要正确缩进。例如:

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 语法。

关于python - 语法错误 : invalid syntax when creating a instance of class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16931461/

相关文章:

python - 为什么当 a 和 b 都为 True 时,我的 <a> 和 <b> if 条件不执行?

javascript - 使用身份证号码隐藏下拉菜单

php - 为什么 PHP 变量前有 $ 符号?

python - 用户定义的函数在 Pycharm 中返回错误值但不是 IDLE

c++ - SWIG: 'module' 对象没有属性 'Decklist'

python - Linux 终端执行 Python 脚本的方式与 Idle 不同

python - 如何在 Python 中将字符串连接到 URL?

python - 为 QTextEdit 设置字体被忽略,没有明显的原因

JavaScript 语法错误

php - 新的 5.4 数组短数组语法 : Good practice?