Search code examples
pythonpython-2.7inheritancemayapymel

How to make a class that returns a child from the hierarchy?


I'm trying to make a class find the type of the object with which it was initialized and I want it to become the object class that corresponds to the type of the object 'typ' that was sent in.

So if if were to do something like the following example, I'd like the variable 'this' to be an instance of TypeA.

How would one go about that?

class Master():
    def __init__(self, typ):
        if typ == 'a':
            return TypeA()
        else:
            return  TypeB()


def TypeA():
    def  __init__(self):
        pass

    def boop():
        print "type A"


def TypeB():
    def  __init__(self):
            pass

    def meep():
        print "type B"



this = Master('a')
this.boop()

(if this means anything to anyone, I want to emulate the behaviour that PyMel has when you create an object with pm.PyNode('object_name'), in which pm.PyNode gives you the lowest child in the hierarchy.)


Solution

  • it seems that you want a factory. maybe something among these lines:

    class Master(object):  # i would rather do a plain function but i'll limit to mimic your lines.
    
        @staticmethod
        def factory(typ, *args, **kwargs):
            mapping = {
                'a': TypeA,
                'b': TypeB
            }
            return mapping[typ](*args, **kwargs)
    

    so then you can call it:

    this = Master.factory('a')
    print this
    
    $ <__main__.TypeA object at 0x7f6cbbec65d0>