Creating alot of class instances?

Christian Heimes lists at cheimes.de
Sun Jul 5 17:42:41 EDT 2009


kk wrote:
> I will be querying some data and create class instances based on the
> data I gather. But the problem as I mentioned is that I do not know
> the names and the number of the end class instances. They will be
> based on the content of the data. So how can I create class instances
> within a loop and when the loop is done how can I figure out the list
> of instances via class membership?  I can track the names by
> introducing another list but I want to understand the class side of
> things.

Do you need an exact number or just a rough statistic? In order to
estimate the number of instances you can query the reference count of
the class. Since every instance usually increases the reference count by
one it provides a good overview. Note that lots of other things like
imports increase the reference count, too.

>>> import sys
>>> class Example(object):
...     pass
...
>>> sys.getrefcount(Example)
5
>>> examples = list(Example() for i in range(10))
>>> examples
[<__main__.Example object at 0x7f2e5cd61110>, <__main__.Example object
at 0x7f2e5cd61150>, <__main__.Example object at 0x7f2e5cd61190>,
<__main__.Example object at 0x7f2e5cd611d0>, <__main__.Example object at
0x7f2e5cd61210>, <__main__.Example object at 0x7f2e5cd61250>,
<__main__.Example object at 0x7f2e5cd61390>, <__main__.Example object at
0x7f2e5cd613d0>, <__main__.Example object at 0x7f2e5cd61410>,
<__main__.Example object at 0x7f2e5cd61450>]
>>> sys.getrefcount(Example)
15



More information about the Python-list mailing list