0

我试图让一个类找到初始化它的对象的类型,我希望它成为与发送的对象“typ”类型相对应的对象类。

因此,如果要执行类似以下示例的操作,我希望变量“this”成为 TypeA 的实例。

一个人会怎么做呢?

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

(如果这对任何人都意味着什么,我想模仿 PyMel 在您使用 pm.PyNode('object_name') 创建对象时的行为,其中 pm.PyNode 为您提供层次结构中最低的孩子。)

4

1 回答 1

1

看来你想要一个工厂。也许在这些方面:

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)

那么你可以调用它:

this = Master.factory('a')
print this

$ <__main__.TypeA object at 0x7f6cbbec65d0> 
于 2017-03-31T00:18:32.997 回答