我在这堂课有什么语法错误?

时间:2019-07-24 04:08:54

标签: python

我正在做一个项目,要求我使用 str 进行打印以作为答案。当我运行此代码时,编译器通过指出return语句来给出语法错误。我很想获得帮助来解决此问题。

我试图删除返回代码周围的括号。

import random
class Movie:
  def __init__ (self, title, year, drname, cat, length):
    self.title = title
    self.year = year
    self.drname = drname
    self.cat = cat
    self.length = length

  def __str__(self):
     return (self.title + '('self.cat','+ self.year')' +'directed by ' + self.drname + ', length ' + self.length + 'minutes')

#Apollo 13 (Drama, 1995) directed by Ron Howard, length 140 minutes
#It should be printed out as shown above

mv1 = Movie("Apollo 13", 1995, 'Ron Howard', 'Drama', 140)

4 个答案:

答案 0 :(得分:4)

除了其他答案之外,我建议使用f字符串(在python 3.6中引入)进行字符串格式化:

return f"{self.title} ({self.cat}, {self.year}) directed by {self.drname} , length  {self.length} minutes"

答案 1 :(得分:1)

您的代码声明'('self.cat','+ self.year')',而没有+

改为使用'(' + self.cat + ',' + self.year + ')'

此外,您可能需要考虑类别和年份之间的空格。如果是这样,请使用以下命令:

'(' + self.cat + ', ' + self.year + ')'

此外,您的yearlength需要转换为字符串,例如使用str(self.length)

答案 2 :(得分:1)

只是一个小的语法错误,您的return语句中缺少加号(+)。

 return (self.title + ' (' + self.cat + ', ' + self.year + ') ' + 'directed by ' + self.drname + ', length ' + self.length + ' minutes.')

这应该有效。

答案 3 :(得分:1)

您应该使用f-string (PEP498)格式化__str__的返回值:

f"{self.title}({self.cat},{self.year}) directed by {self.drname}, length {self.length} minutes"

您的代码,PEP8和有效代码:

class Movie:
    def __init__(self, title, year, drname, cat, length):
        self.title = title
        self.year = year
        self.drname = drname
        self.cat = cat
        self.length = length

    def __str__(self):
        return f"{self.title} ({self.cat}, {self.year}) directed by {self.drname}, length {self.length} minutes"


# Apollo 13 (Drama, 1995) directed by Ron Howard, length 140 minutes
# It should be printed out as shown above    

mv1 = Movie("Apollo 13", 1995, 'Ron Howard', 'Drama', 140)
print(mv1)

输出:

Apollo 13 (Drama, 1995) directed by Ron Howard, length 140 minutes