Python class called Movie that you can use to store movie information from text files and achieve the desired functionality:
class Movie:
def __init__(self, name, director, year):
self.name = name
self.director = director
self.year = year
self.score = None
def set_score(self, score):
self.score = score
def __str__(self):
if self.score is None:
return f"{self.name} ({self.year})"
else:
return f"{self.name} ({self.year}) - Score: {self.score}"
# Assuming you have text files named "1.txt" to "20.txt"
movies = []
for i in range(1, 21):
filename = f"{i}.txt"
with open(filename, "r") as file:
lines = file.readlines()
name = lines[0].strip()
director = lines[1].strip()
year = lines[2].strip()
movie = Movie(name, director, year)
movies.append(movie)
# Set scores for some movies (optional)
movies[0].set_score(8.5)
movies[5].set_score(7.9)
movies[15].set_score(9.2)
# Print movie information
for movie in movies:
print(movie)
In this code, the Movie class is defined with an __init__ constructor to initialize the movie's name, director, and year of production. The set_score method is used to set the movie's score. The __str__ method is overridden to customize the string representation of the Movie object, displaying the name and year of production (and score, if available) when printed.
The code then reads movie information from text files (assuming they're named from "1.txt" to "20.txt") and creates Movie objects accordingly. It sets scores for some movies (you can adjust this as needed) and finally, it prints out the movie information using the customized string representation defined in the __str__ method.