0

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.)

martineau
  • 119,623
  • 25
  • 170
  • 301
Arturo
  • 171
  • 1
  • 17
  • 1
    First, you will want to write a plain function, not a class, for `Master`. Second, you will want to use a dictionary rather than a cascade of `if` statements to translate the strings into classes. – kindall Mar 31 '17 at 00:12
  • 1
    See [**_Improper use of __new__ to generate classes?_**](http://stackoverflow.com/questions/28035685/improper-use-of-new-to-generate-classes) – martineau Mar 31 '17 at 00:16
  • Ahh, yes. it looks like i was complicating my life. a method is the better way. Thanks. – Arturo Mar 31 '17 at 00:20

1 Answers1

1

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> 
odradek
  • 993
  • 7
  • 14