En Sun, 25 Jan 2009 16:06:47 -0200, Andreas Waldenburger
<geekm...@usenot.de> escribió:
On Sun, 25 Jan 2009 09:23:35 -0800 (PST) Kottiyath
<n.kottiy...@gmail.com> wrote:
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
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).
See http://bugs.python.org/issue1717900
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list