-2

So i have class which construct i already have made and i need to make function for str print method. And i dont know how to call that str method in other functions of the same class

Here is the construct and str method

class Movie:
  def __init__(nameofmovie,dateofpremiere,howlong,typeofmovie):
    self.nameofmovie=nameofmovie
    self.dateofpremiere=dateofpremiere
    self.howlong=howlong
    self.typeofmovie=typeofmovie

  def __str__(self):
    print(+self.nameofmovie, +str(self.dateofpremiere), +str(self.howlong),+self.typeofmovie)

  

Now how i can call that str method in other functions.

Minko
  • 1
  • 3
  • 2
    ``__str__`` must *return* a string, not print it. Also, strings do not support a unary ``+`` – each use of ``+`` inside ``__str__`` is an error. – MisterMiyagi Aug 18 '20 at 10:49
  • 1
    What have you tried so far to call the ``__str__`` method? Do you know how to call other methods? Do you know how to "call" ``__str__`` from outside the class? Why did you define a ``__str__`` method when you do not know how to call it? – MisterMiyagi Aug 18 '20 at 10:51

1 Answers1

0

EDIT: First of all, every function in a class (that isn't a static or class method, e.g. needs a class instance) needs to accept self as first parameter.

Second, private str function is used when calling print with your class so this would work:

class Movie:
  def __init__(self, nameofmovie,dateofpremiere,howlong,typeofmovie):
    self.nameofmovie=nameofmovie
    self.dateofpremiere=dateofpremiere
    self.howlong=howlong
    self.typeofmovie=typeofmovie

  def __str__(self):
    return f'{self.nameofmovie} {str(self.dateofpremiere)} {str(self.howlong)} {self.typeofmovie}'


movie = Movie('hello', '23/5/2020', '1', 'horror')
print(movie)

Prints hello 23/5/2020 1 horror

You may add:

def print(self):
      print(self.__str__())

To your class and then call:

movie = Movie('hello', '23/5/2020', '1', 'horror')
movie.print()
Shimon Cohen
  • 489
  • 3
  • 11
  • so when i want to create another function in that class and in that function when i want to print something how im going to call __str__ function, am i only going to type s.__str__() or ? – Minko Aug 18 '20 at 10:50
  • You would call it with self.__str__(). There may be another way im not aware of. – Shimon Cohen Aug 18 '20 at 10:57