实例化变量中名为的对象

2024-05-13 19:13:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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”的胡说八道吗?你知道吗


Tags: 对象实例self列表def组件容器class
1条回答
网友
1楼 · 发布于 2024-05-13 19:13:48

你差点就到了,但问题不是你的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())是一样的,但是现在通过一个变量调用。你知道吗

相关问题 更多 >