Python:弄清楚"配偶"类?

No *_*ame 5 python oop class multiple-inheritance

所以这里我有一个问题.假设我有2个父类.它们都继承自大师班.然后它们都是子类的父类.有没有办法弄清楚(让我说我是父亲)哪个母班我是"生孩子?" 我不需要孩子弄清楚哪个母亲班,我希望父能够弄清楚它是哪个母班.

我知道这是一个愚蠢的例子,但它是我在其他地方必须做的简化版本.

class Master(object):
    def __init__(self):
        self.troll()
        self.trell()

class Mother1(Master):
    def troll(self):
        print 'troll1'

class Mother2(Master):
    def troll(self):
        print 'troll2'

class Father(Master):
    def trell(self):
        print 'trell'
        print self.figure_out_spouse_class()

class Child1(Mother1, Father):
    pass

class Child2(Mother2, Father):
    pass

c = Child1() #should print 'Mother1'
c = Child2() #should print 'Mother2'
Run Code Online (Sandbox Code Playgroud)




Dav*_*son 6

你可以使用__bases__:

def figure_out_spouse_class(self):
    return [b.__name__ for b in self.__class__.__bases__ if b != Father]
Run Code Online (Sandbox Code Playgroud)

(如果有多个"配偶"类,这将返回所有"配偶"类的名称).