实例化变量中指定的对象

时间:2013-01-25 13:46:42

标签: python object instantiation

我有一个组件对象库。我想在另一个对象中包含对这些对象的选择的实例化。但我想将该选择作为列表提供,以便每次使用列表实例化容器对象时,都会使用其中的指定子对象创建它。

假设我的组件库如下所示:

class ColorBlob(object):
    ...
    def wipeItUp()
        ...

class RedBlob(ColorBlob):
    ...
    def paintIt()
        ...
class YellowBlob(ColorBlob):
    ...
    def paintIt()
        ...
class BlueBlob(ColorBlob):
    ...
    def paintIt()
        ...

我的容器对象如下所示:

class Pallet(object):
    def __init__(self, colorList):
        for color in colorList:
            #Ok, here is where I get lost if I know the color I can do this:
            Pallet.BlueBlob = blobLib.BlueBlob()
            #But I don't, so I am trying to do something like this:
            blobSpecs       = getattr(blobLib, color)
            blobSpecs.Obj   = blobSpecs().returnObj(self.page) # with "returnObj" defined in the library as some other method
            setattr(self, Pallet.blobName, blobSpecs) #and I am completely lost.

但我在功能代码中真正想做的是:

workingPallet=Pallet(['RedBlob', 'BlueBlob'])
workingPallet.RedBlob.paintIt()

我知道当我尝试在容器中实例化子对象时,我迷失了。有人能帮助我理顺我的“getattr”和“setattr”废话吗?

1 个答案:

答案 0 :(得分:2)

你几乎就在那里,但不是你的getattrsetattr问题。您最终将该类设置回self,而不是您创建的实例:

def __init__(self, colorList):
    for color in colorList:
        blobSpec       = getattr(blobLib, color)
        blob           = blobSpec()    # create an instance of the blob
        blob.Obj       = blob.returnObj(self.page) 
        setattr(self, color, blob)

与直接调用类(BlueBlob())完全相同,但现在通过变量调用。