class return another instance

Keith python at cgcreator.com
Tue Aug 8 08:43:39 EDT 2006


Hello All,

 

Here is simplified version of what I'm trying to do:

 

////////////////////////////////////////////////////////////////////////////
////////////////////////////

 

IDs = {}

 

class ID:

            def __init__(self, id):

                        if id in IDs:

                                    self = IDs[id]

                        else:

                                    IDs[id] = self

                        

foo = ID(1)

bar = ID(2)

 

copy = ID(1)

 

print "foo: " + str(foo) + " with ID of 1"

print "bar: " + str(bar) + " with ID of 2"

print "copy: " + str(copy) + " should be a copy of foo"

 

print "IDs: " + str(IDs)

 

 

////////////////////////////////////////////////////////////////////////////
////////////////////////////

 

What I'm after is if you call the class ID. it checks to is if the "id" is
in the dictionary IDs. if so then use that class instance. else put self
into the dictionary as a new key-value, so if you try and create it again.
it will use that instance.

 

Also I know its easy enough to do copy = foo. but I would like the class to
determine this for me. any ideas?

 

There has got to be a way to replace self with another instance. or return
something from the init statement.

 

 

Here's what it returns:

foo: <__main__.ID instance at 0x01DE6CB0> with ID of 1

bar: <__main__.ID instance at 0x01DE6CD8> with ID of 2

copy: <__main__.ID instance at 0x01DE6D00> should be a copy of foo

IDs: {1: <__main__.ID instance at 0x01DE6CB0>, 2: <__main__.ID instance at
0x01DE6CD8>}

 

 

What I would expect/want:

foo: <__main__.ID instance at 0x01DE6CB0> with ID of 1

bar: <__main__.ID instance at 0x01DE6CD8> with ID of 2

copy: <__main__.ID instance at *0x01DE6CB0*> should be a copy of foo

IDs: {1: <__main__.ID instance at 0x01DE6CB0>, 2: <__main__.ID instance at
0x01DE6CD8>}

 

 

Any help would be great.

 

Cheers,

Keith

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20060808/a6a7e0ac/attachment.html>


More information about the Python-list mailing list