Counting number of objects
gagsl-py2 at yahoo.com.ar
Sun Jan 25 23:49:00 CET 2009
En Sun, 25 Jan 2009 16:06:47 -0200, Andreas Waldenburger
<geekmail at usenot.de> escribió:
> On Sun, 25 Jan 2009 09:23:35 -0800 (PST) Kottiyath
> <n.kottiyath at gmail.com> wrote:
>> I am creating a class called people - subclasses men, women, children
>> 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):
> This looks OK, although I'd suggest using "cls.counter += 1" instead of
> "a.counter += 1" in the __new__() method. Just seems clearer to me,
> esp. when you think about subclassing. This would create an asymmetry
> with __del__() then. Oh well. So maybe use "self.__class__.counter -= 1"
> there, even if it is a bit ugly-ish.
Using self.__class__ is safer, from a technical point of view. When
__del__ is executed at interpreter shutdown, "a" may not be available --
in general, __del__ methods should not rely on any globals (one can
"inject" names into the local namespace using default arguments).
More information about the Python-list