多重继承 - Child class 随机选择方法的问题

Multiple inheritance - Child class problem in randomly choosing a method

我的代码应该让 Parrot class 只随机选择一种说话方式,代码目前所做的是同时重复所有行。

This is my ninja way!
Hi, I am Goku!
Give me your strength Pegasus!
None
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()

那是因为您在 choice() 调用中调用了所有方法。 先选择方法,再调用。

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

此外,此方法将始终在调用后打印 None,因为您的方法不会 return 任何内容。所以也许这更接近你想要的:

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

并且由于 Parrot 从超类继承而没有覆盖方法,您可以只在实例上访问它。

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

您不需要 super,因为 Parrot 没有 覆盖 任何继承的方法。但是你也需要先选择一个方法,然后调用选择的方法。

class Parrot(Naruto, Goku, Seiya):
    def repeat(self):
        m = random.choice([self.talk1,
                           self.talk2,
                           self.talk3]
                         )
        m()

如果所有 three parent 类 定义 talk 不同,你可以做类似

class Parrot(Naruto, Goku, Seiya):
    def repeat(self):
        cls = random.choice([Parrot, Naruto, Goku])
        super(cls, self).talk()