为什么有一个错误代码,该属性在这个类中显然不存在

时间:2017-06-26 17:01:42

标签: python

我正在使用Python 2.7.13 这些是我的文件:

C:\项目\ movies_pythonproject \ Media.py

import webbrowser

class Movie():
    def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
        self.title = movie_title
        self.storyline = movie_storyline
        self.poster_image_url = poster_image
        self.trailer_youtube_url = trailer_youtube

        def show_trailer(self):
            webbrowser.open(self.trailer_youtube_url)

C:\项目\ movies_pythonproject \ entertainmentcenter.py

import media
Above_The_Law = media.Movie("Above The Law",
                        "A former Special Operations Vietnam vet works as a 
Chicago cop and uncovers CIA wrongdoing.",
                        "https://images-na.ssl-images-amazon.com/images/M/MV5BYTgyYTIyOTMtMmQzMC00MDVlLTg0YjItMDVmYjczMzY2ODM1XkEyXkFqcGdeQXVyNjQ2MjQ5NzM@._V1_UY268_CR0,0,182,268_AL_.jpg",
                        "https://youtu.be/GZjl-UT4-o4" )

Above_The_Law.show_trailer()

当我运行entertainmentcenter.py时,控制台会给我这个错误:

Traceback (most recent call last):
 File "C:/PROJECTS/movies_pythonproject/entertainment_center.py", line 8, in 
<module>
  Above_The_Law.show_trailer()
AttributeError: Movie instance has no attribute 'show_trailer'
>>> 

1 个答案:

答案 0 :(得分:3)

您的问题是缩进问题。

您将show_trailer方法定义为__init__方法中的本地方法。

你想要的是:

class Movie():
    def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
        self.title = movie_title
        self.storyline = movie_storyline
        self.poster_image_url = poster_image
        self.trailer_youtube_url = trailer_youtube

    def show_trailer(self):
        webbrowser.open(self.trailer_youtube_url)