-1
我正在嘗試創建一個名爲Movie的類。我已經聲明瞭實例變量。我打電話給OMDB API,我想存儲分配變量。但這似乎並沒有奏效。即使當我打印json_Data時,它也不會打印任何東西。任何人都可以指向正確的方向。我知道我可以將數據存儲到字典中。但是它將如何存儲在一個類中。我是一個仍在學習python的newbiew。Python:Json數據到類實例變量中
class Movie(object):
""" Class provides a structure to store Movie information """
def __init__(self, imdb_id, title = None, release_year = None, rating = None, run_time = None, genre = None, director = None, actors = None, plot = None, awards = None, poster_image = None, imdb_votes = None, youtube_trailer = None):
self.imdb_id = imdb_id
self.title = title
self.release_year = release_year
self.rating = rating
self.run_time = run_time
self.genre = genre
self.director = director
self.actors = actors
self.plot = plot
self.awards = awards
self.poster_image = poster_image
self.imdb_votes = imdb_votes
self.youtube_trailer = youtube_trailer
def get_api_data(self):
"""
Method retreves and parses information for each movie based on imdb_id
"""
#URL for OMDBI
url = "http://www.omdbapi.com/?i="+self.imdb_id+"&plot=full&r=json&v=1"
try:
response = urllib.urlopen(url)
except URLERROR as e:
if hasattr(e, 'reason'):
print ("Unable to reach a server.")
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print "Server is unable to fulfill the request."
print 'Error Code: ', e.code
else:
json_data = json.loads(response.read())
self.imdb_id = json_data["imdbID"].encode("utf8","ignore")
self.title = json_data["Title"].encode("utf8","ignore")
self.release_year = int(json_data["Released"].split("")[-1])
self.rating = json_data["imdbRating"].encode("utf8", "ignore")
self.run_time = json_data["Runtime"].encode("utf8", "ignore")
self.genre = json_data["Rated"].encode("utf8", "ignore")
self.director = json_data["Director"].encode("utf8", "ignore")
self.actors = json_data["Actors"].encode("utf8", "ignore")
self.plot = json_data["Plot"].encode("utf8", "ignore")
self.awards = json_data["Awards"].encode("utf8", "ignore")
self.poster_image = json_data["Poster"].encode("utf8", "ignore")
self.imdb_votes = json_data["imdbVotes"].encode("utf8", "ignore")
是否建議將返回的數據存儲爲字典,而不是爲每種電影類型創建類?
最後的else:仍然在except子句中,所以如果try:成功,你的代碼永遠不會到達那個塊。 –