How to control the creation of an instance?

7stud bbxx789_05ss at yahoo.com
Sun Jun 3 02:17:33 EDT 2007


On Jun 2, 10:31 pm, lialie <lia... at gmail.com> wrote:
> Hi,
>
> suppose i have a free_object list[Sample1, Smaple2....]. when create a
> new object sample(*args, **kwds), if free_object_list isn't empty, just
> pop one from free_object_list instead of creating a new instance.
>
> any way to do this?
>
> I do some work as follows:
>
> class Sample(object):
> used_object = []
> free_object = []
>
> def __init__(self, *args, **kwds):
> pass
>
> def __new__(self, *args, **kwds):
> if Sample.free_object:
> obj = Sample.free_object.pop(0)
> else:
> obj = object.__new__(Sample, *args, **kwds)
> Sample.used_object.append(obj)
> return obj
>
> ######## still get a new instance :(
>
> def Release(self):
> Sample.used_object.remove(self)
> Sample.free_object.append(self)
> return True

This seems to work for me:

import collections

class Sample(object):

    free_objects = collections.deque()
    used_objects = []

    def __new__(cls, *args, **kwds):
        if not Sample.free_objects:
            temp = object.__new__(Sample, args, kwds)
            Sample.used_objects.append(temp)
            return temp
        else:
            return Sample.free_objects.popleft()

    def __init__(self, *args, **kwds):
        self.args = args
        self.kwds = kwds

    def release(self):
        Sample.used_objects.remove(self)
        Sample.free_objects.append(self)

s1 = Sample(10, name="Bob")
print s1
print s1.args
print s1.kwds

s2 = Sample("red", name="Bill")
print s2
print s2.args
print s2.kwds

s1.release()
s3 = Sample("blue", name="Tim")
print s3
print s3.args
print s3.kwds




More information about the Python-list mailing list