Dictionary of classes
Robert Sherwood
foofboy at speakeasy.net
Mon Dec 3 08:06:17 EST 2001
On Sat, 01 Dec 2001 11:45:29 -0500, Robert Sherwood wrote:
> Greetings, all.
>
> I would like to construct and use a dictionary containing object
> references. I'm translating a binary file stream to an object structure,
> and I'd like to use the parts of the binary stream that identify the
> data as keys in a dictionary which will return an object reference which
> the main program can then instantiate and populate from the data stream.
> I know that it's possible to store objects as the value in a dictionary.
> Has anyone seen this done in the wild. Best of all would be a pointer to
> some code implementing such a feature.
>
> Any help would be appreciated. An example of what I'm trying is attached
> below.
>
> Thanks,
>
> Robert Sherwood
>
> frameID = self.headerArray[:4].toString() try:
> frame = objectDict[frameID]()
> frame.decode(self.popFrame())
> self.frames[frame.getFrameID()] = frame
> except KeyError:
> frame = unknownFrame()
> frame.decode(self.popFrame())
> self.frames[frame.getFrameID()] = frame
>
> where the objectDict looks like this.
>
> objectDict = {
> '0001':object1,
> '0002':object2,
> '0003':object3,
> }
Okay. Got some help from a few subscribers. Thanks to everyone that
responded.
Apparently that code is fine, but, on reflection, it's not actually what
I want to do. Turns out I want to implement a mapping object that
wraps around a dictionary. I've implemented a very simple method for
__getitem__, that shunts key queries to the dictionary and returns the
result. Having defined the object, I now get an unsubscriptable object
error whenever I try to lookup a key. Example code follows:
----------------------------
import objectDict
frameID = self.headerArray[:4].toString() try:
frame = objectDict[frameID]() <---Returns "unsubscriptable Object"
frame.decode(self.popFrame())
self.frames[frame.getFrameID()] = frame
except KeyError:
frame = unknownFrame()
frame.decode(self.popFrame())
self.frames[frame.getFrameID()] = frame
------------------------------
class objectDict:
memberDict = {
'0001':object1,
'0002':object2,
'0003':object3,
}
def __getitem__:
return self.memberDict[key]
More information about the Python-list
mailing list