How to control the creation of an instance?

7stud bbxx789_05ss at yahoo.com
Sun Jun 3 01:13:08 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

Try something like this:

class A(object):
    pass

def getObj(alist):
    if alist:
        return alist.pop()
    else:
        return A()

x = [A(), A()]
print x

newlist = []
for i in range(0,3):
    newlist.append(getObj(x) )

print newlist

--output:--
[<__main__.A object at 0x55bf0>, <__main__.A object at 0x55b50>]
[<__main__.A object at 0x55b50>, <__main__.A object at 0x55bf0>,
<__main__.A object at 0x55d30>]


Examine the addresses, i.e. the set of numbers in each <....>




More information about the Python-list mailing list