-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:が成功するとコードは決してそのブロックに到達しません。 –