I have a library of component objects. I would like to include instantiations of a selection of those objects in another object. But I would like to provide that selection as a list so that each time I instantiate the container object with a list, it will be created with the specified sub objects in it.
Let’s say my component library looks like this:
class ColorBlob(object):
...
def wipeItUp()
...
class RedBlob(ColorBlob):
...
def paintIt()
...
class YellowBlob(ColorBlob):
...
def paintIt()
...
class BlueBlob(ColorBlob):
...
def paintIt()
...
And my container object looks like this:
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.
But what I really want to do in my functional code is this:
workingPallet=Pallet(['RedBlob', 'BlueBlob'])
workingPallet.RedBlob.paintIt()
I know that I am lost when I try to instantiate the sub objects in the container. Can someone help me straighten out my “getattr” and “setattr” nonsense?
You were almost there, but it isn’t your
getattrorsetattrthat’s the problem. You end up setting the class back onself, not the instance you created:It’s the same thing as calling the class directly (
BlueBlob()), but now through a variable.