SyntaxError:创建类的实例时语法无效 [英] SyntaxError: invalid syntax when creating a instance of class
问题描述
我在 Python shell 3.3.2 中运行此代码,但它给了我 SyntaxError: invalid syntax
.
类动物(对象):"""制作可爱的动物."""is_alive = 真def __init__(自我,姓名,年龄):self.name = 姓名self.age = 年龄定义描述(自我):打印 (self.name)打印 (self.age)hippo = Animal("2312",21)#该行发生错误河马.描述()
我是 Python 新手,不知道如何修复此代码.
您没有正确缩进代码.您的方法主体缩进正确,但您忘记缩进文档字符串和方法的 def
语句,以及 is_alive = True
语句.如果您像这样在 IDLE 中输入它,它将起作用:
块语句的主体是位于 :
之后的任何内容,它需要适当缩进.例如:
如果'a' == 'b':print('这永远不会打印')别的:print('当然a不等于b!')
如果你这样输入:
如果'a' == 'b':print('这永远不会打印')别的:print('当然a不等于b!')
它不是有效的 Python 语法.
I run this code in Python shell 3.3.2, but it gives me 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()
I'm a newbie in Python and I don't know how fix this code.
You didn't indent your code properly. The body of your methods is indented correctly, but you forgot to indent the doc string, and the def
statement for your methods, in addition to the is_alive = True
statement. If you type it in IDLE like this, it will work:
>>> 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
The body of a block statement is anything that comes after a :
, and it needs to be properly indented. for example:
if 'a' == 'b':
print('This will never print')
else:
print('Of course a is not equal to b!')
If you type it like this:
if 'a' == 'b':
print('This will never print')
else:
print('Of course a is not equal to b!')
It is not valid Python syntax.
这篇关于SyntaxError:创建类的实例时语法无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!