Python:为什么这里的语法无效? [重复]

问题描述 投票:0回答:4

我在 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 #error occurs in that line!
        print self.age

hippo=Animal('2312','321312')
hippo.description()

我是Python新手,我不知道如何修复这些代码。谁能给我一些建议吗?预先感谢。

python syntax
4个回答
3
投票

print
是Python 3中的一个函数,而不是早期版本中的关键字。您必须将参数括在括号中。

def description(self):
    print(self.name)
    print(self.age)

2
投票

print
是一个函数(参见文档):

你想要:

...
def description(self):
    print(self.name)
    print(self.age)
...

2
投票

您正在使用

print
作为陈述。 Python 3 中不再是一条语句;现在它是一个函数。只需将其作为函数调用即可。

print(self.name)
print(self.age)

2
投票

在 python 3 中,

print self.name
无效。

应该是

print (self.name)
print (self.age)
© www.soinside.com 2019 - 2024. All rights reserved.