0

我正在做一个需要我使用str打印出来作为答案的项目。当我运行这段代码时,编译器通过指出返回语句来给出语法错误。我很想得到帮助来解决这个问题。

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

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

4 回答 4

4

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

return f"{self.title} ({self.cat}, {self.year}) directed by {self.drname} , length  {self.length} minutes"
于 2019-07-24T04:24:04.313 回答
1

您的代码状态'('self.cat','+ self.year')'没有+.

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

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

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

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

于 2019-07-24T04:11:20.887 回答
1

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

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

这应该有效。

于 2019-07-24T04:17:52.830 回答
1

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

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
于 2019-07-24T04:29:02.993 回答