【问题标题】:AttributeError: 'tuple' object has no attribute 'year'AttributeError:“元组”对象没有属性“年”
【发布时间】:2020-06-13 09:25:37
【问题描述】:

This is the error I'm getting 我应该用 3 部不同的电影创建 3 个类电影的实例,但我一直遇到属性错误。我不知道如何解决。我是 OOPS 概念的新手。

class Movie:
    # create class here
    def __init__(self, title, director, year):
        self.title = title
        self.director = director
        self.year = year
# objects of the class Movie
titanic = Movie("Titanic", "James Cameron", "1997")
star_wars = Movie("Star Wars", "George Lucas", "1977"),
fight_club = Movie("Fight Club", "David Fincher", "1999")

【问题讨论】:

  • 您能否分享导致错误的实际代码和堆栈跟踪,因为您粘贴的代码不会产生任何错误。
  • 这是产生错误的实际代码。我直接从窗口复制并粘贴了它。截图有用吗?
  • 我已经运行了你的代码,它没有给出任何错误。一定有比这更多的代码,你的代码中一定有一些东西在某个时候你试图访问 year 但可能不小心为变量分配了一个元组。现在该错误无法重现,查看您发布的当前代码,我看不出它如何在标题中给出属性错误。
  • 当您尝试访问其中一个对象的年份时是否会出现此问题?
  • 我已经用图片编辑了问题供您参考。

标签: python-3.x class oop object


【解决方案1】:

您需要删除倒数第二行的尾随逗号,因为 python 将其视为包含电影的单项元组。

改变

star_wars = Movie("Star Wars", "George Lucas", "1977"),

star_wars = Movie("Star Wars", "George Lucas", "1977")

您可以通过查看对象来了解发生了什么。

print(type(star_wars))
print(type(star_wars[0]))
print(star_wars[0].year)
<class 'tuple'>
<class '__main__.Movie'>
1977

【讨论】:

    猜你喜欢
    • 2013-06-21
    • 2021-07-30
    • 2013-07-29
    • 2020-08-29
    • 2015-04-22
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多