Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Figure out "Spouse" class?

So here I have a problem. Let's say I have 2 parent classes. They both inherit from a master class. Then they are both parent classes to a child class. Is there a way to figure out (let's say I'm Father) which Mother class I'm "having a child with?" I don't need the child to figure out which mother class, I want the Father to be able to figure out which mother class it is.

I know this is a silly example, but it's a simplified version of what I have to do elsewhere.

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'

~
~
~
~

like image 932
John Avatar asked Aug 01 '12 01:08

John


1 Answers

You can use __bases__:

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

(This would return the names of all "spouse" classes if there are more than one).

like image 158
David Robinson Avatar answered Nov 15 '22 10:11

David Robinson