Counting number of objects

Steve Holden steve at
Sun Jan 25 18:39:19 CET 2009

Kottiyath wrote:
> Hi,
> I am creating a class called people - subclasses men, women, children
> etc.
> I want to count the number of people at any time.
> So, I created code like the following:
> class a(object):
>     counter = 0
>     def __new__(cls, *args, **kwargs):
>         a.counter += 1
>         return object.__new__(cls, *args, **kwargs)
>     def __del__(self):
>         a.counter -= 1
> class aa(a):
>     pass
> Now, the code works Ok. I have the following questions:
> 1. Is this code Ok? Is there any straightforward mechanism other than
> this to get the number of objects?
> 2. I read in Python Documentation that inside __del__ we should the
> minimum of interaction with external parameters. So, I am a little
> worried in subclassing __del__ to check the counter. Is whatever I
> have done Ok?
Yes. Just be aware that if instances become involved in cyclic data
structures (or in implementations other than CPython, where reference
counting isn't used) __del__ might not be called until garbage
collection kicks in, so you may want a more explicit way to stop an
instance from being in the count.

> Another question - unrelated to the major topic:
> How much time does it take to be proficient in Python? I have been
> working exclusively in Python for close to 3 months now, and even now
> I get inferiority complex when I read the answers sent by many of you.
> I have been programming for close to 7 years now (earlier in a
> language similar to COBOL).
> Does it take quite a bit of time to be proficient - as many of you
> guys - or am I just dumb?

By your code above you seem to be doing OK. Python is like an iceberg -
only an eighth of what goes on is above the surface. That eighth will
suffice for many people's total programming needs.

I've been using Python ten years, and I am still learning. Just go at
your own pace, and carry on asking for help when you need it.

Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC    

More information about the Python-list mailing list