Is there a way I can make a function that carries out the bottom Task, without having to rewrite it for each new variable?

Question:

I am trying to make a program with loads of films where i can call them using Classes (I am very new to classes and still trying to figure out how they work). Is there a way I can create the function for the bottom 3 lines that can does this automatically? Kind of like the Get functions I have put in, I tried imbedding this into one function but got the error code that the functions where not defined.

class Film():
   def __init__(self, name, genre, rating):
        self.name = name
        self.genre = genre
        self.rating = rating #0-100 
    
   def get_name(self):
        return ("The Name of the film is: " + str(self.name))
   def get_genre(self):
        return ("The Genre of the film is: " + str(self.genre))
   def get_rating(self):
        return ("The rating of the film is: " + str(self.name))

    
f1 = Film("Fight Club", "Thriller", 91)
f2= Film("Whiplash","Thriller",86)
f3 = Film("Inside out","Animation",71)

print(f1.get_name(), f1.get_genre(), f1.get_rating())
print(f2.get_name(), f2.get_genre(), f2.get_rating())
print(f3.get_name(), f3.get_genre(), f3.get_rating())
Asked By: DannyMoham1

||

Answers:

I think you can just do following:

class Film():
   def __init__(self, name, genre, rating):
        self.name = name
        self.genre = genre
        self.rating = rating #0-100

   def get_all(self):
        return (self.name, self.genre, self.rating)

    
f1 = Film("Fight Club", "Thriller", 91)
f2= Film("Whiplash","Thriller",86)
f3 = Film("Inside out","Animation",71)

print(f1.get_all())
print(f2.get_all())
print(f3.get_all())

or

class Film():
   def __init__(self, name, genre, rating):
        self.name = name
        self.genre = genre
        self.rating = rating #0-100

    
f1 = Film("Fight Club", "Thriller", 91)
f2= Film("Whiplash","Thriller",86)
f3 = Film("Inside out","Animation",71)

print(f1.name, f1.genre(), f1.rating())
print(f2.name(), f2.genre(), f2.rating())
print(f3.name(), f3.genre(), f3.rating())

or

print(f1.__dict__["__doc__"])
print(f2.__dict__["__doc__"])
print(f3.__dict__["__doc__"])

Reference: https://stackoverflow.com/a/68900928/20443541

Answered By: kaliiiiiiiii

Welcome to Python! What you may want is the __str__ operator of any Python class:

class Film:
    def __init__(self, name, genre, rating):
        self.name = name
        self.genre = genre
        self.rating = rating #0-100

    def __str__(self):
       return f"""
       The Name of the film is: {self.name}
       The Genre of the film is: {self.genre}
       The rating of the film is: {self.rating}
       """

f1 = Film("Fight Club", "Thriller", 91)
f2= Film("Whiplash","Thriller",86)
f3 = Film("Inside out","Animation",71)

print(f1)
print(f2)
print(f3)            

Note that I’ve used f-strings, which is the modern way to format text that uses the values of local variables.

Finally, if what you wish is to not print but maybe use the attributes of an instance to do something else, you must use the self keyword:

def do_something_with_my_attrs(self):
    rating_plus_ten = self.rating + 10
    return f"I'm {self.name} and my rating plus ten is {rating_plus_ten}."
Answered By: JustLearning

You could use __str__ magic function:

class Film():
    def __init__(self, name, genre, rating):
        self.name = name
        self.genre = genre
        self.rating = rating  # 0-100

    def get_name(self):
        return ("The Name of the film is: " + str(self.name) + "n")

    def get_genre(self):
        return ("The Genre of the film is: " + str(self.genre) + "n")

    def get_rating(self):
        return ("The rating of the film is: " + str(self.name) + "n")

    # Here you use the "magic function"
    def __str__(self):
        return self.get_name() + self.get_genre() + self.get_rating()

f1 = Film("Fight Club", "Thriller", 91)
f2 = Film("Whiplash", "Thriller", 86)
f3 = Film("Inside out", "Animation", 71)

# Now you can directly print the information you want.
print(f1)
print(f2)
print(f3)

Here the result:

The Name of the film is: Fight Club
The Genre of the film is: Thriller
The rating of the film is: Fight Club

The Name of the film is: Whiplash
The Genre of the film is: Thriller
The rating of the film is: Whiplash

The Name of the film is: Inside out
The Genre of the film is: Animation
The rating of the film is: Inside out
Answered By: IvanJijon

There are various ways to achieve what you are asking for. It is hard to say what would be the best case for you without any context.
Here are a few ways you can abstract the last 3 lines from your sample code:

def get_film_details(film):
return f"{film.get_name()}, {film.get_genre()}, {film.get_rating()}"


print(get_film_details(f1))
print(get_film_details(f2))
print(get_film_details(f3))

def get_film_details_from_list(film_list):
    return 'n'.join([f"{film.get_name()}, {film.get_genre()}, 
{film.get_rating()}" for film in film_list])

print(get_film_details_from_list([f1, f2, f3]))
Answered By: artem

You can use the builtin vars function to grab all the fields. This is useful if you want to add additional fields to your Film class. I also used list comprehension to perform all the print statements, but it’s just a flourish.

class Film():
    def __init__(self, name, genre, rating, star):
        self.name = name
        self.genre = genre
        self.rating = rating #0-100 
        self.starring = star

    def get_name(self):
        return ("The Name of the film is: " + str(self.name))
    def get_genre(self):
        return ("The Genre of the film is: " + str(self.genre))
    def get_rating(self):
        return ("The rating of the film is: " + str(self.name))


f1 = Film("Fight Club", "Thriller", 91, 'Brad Pitt')
f2 = Film("Whiplash","Thriller",86, 'J.K. Simmons')
f3 = Film("Inside out","Animation",71, 'Amy Poehler')

# print(f1.get_name(), f1.get_genre(), f1.get_rating())
# print(f2.get_name(), f2.get_genre(), f2.get_rating())
# print(f3.get_name(), f3.get_genre(), f3.get_rating())

films = [f1, f2, f3]

output = [print(f'The name of the film is {name} in the {genre} genre with a rating of {rating} starring {star}.') 
          for film in films 
          for (name,genre,rating, star) in [vars(film).values()]]
Answered By: Michael Cao
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.