Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple inheritance – Child class problem in randomly choosing a method

My code should make the Parrot class randomly choose only one method of speaking, what the code currently does is repeat all the lines at the same time.

  • Current output
This is my ninja way!
Hi, I am Goku!
Give me your strength Pegasus!
None
  • Code
import random

class Naruto():
    def talk1(self):
        print("This is my ninja way!")

class Goku():
    def talk2(self):
        print("Hi, I am Goku!")

class Seiya():
    def talk3(self):
        print("Give me your strength Pegasus!")

class Parrot(Naruto, Goku, Seiya):
    def repeat(self):
        print(random.choice((super().talk1(), super().talk2(), super().talk3())))

parrot = Parrot()
parrot.repeat()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

That’s because you call all methods in the choice() call.
Choose the method first, and then call it.

class Parrot(Naruto, Goku, Seiya):
    def repeat(self):
        print(random.choice((super().talk1, super().talk2, super().talk3))())

Also this method will always print None after the call, since your methods do not return anyting. So maybe that’s closer to what you want:

class Parrot(Naruto, Goku, Seiya):
    def repeat(self):
        random.choice((super().talk1, super().talk2, super().talk3))()

And since Parrot inherits from the superclasses without the methods being overridden, you can just access it on the instance.

class Parrot(Naruto, Goku, Seiya):
    def repeat(self):
        random.choice((self.talk1, self.talk2, self.talk3))()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading