<分区>
我在 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 的新手,我不知道如何修复这段代码。
您没有正确缩进代码。您的方法主体缩进正确,但除了 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 语法。