pretty basic instantiation question

Steven D'Aprano steve at
Tue Oct 24 03:14:29 CEST 2006

On Mon, 23 Oct 2006 17:36:14 -0700, meithamj wrote:

[fixing top-posting]

> sittner at wrote:
>> i'm very new to python, but i have a pretty basic question:
>> let's say i have a class, and i need to create a different number of
>> instances (changes every time - and i can't know the number in advance) in
>> a loop.

As others have pointed out, the answer is "don't do that, use a list of
instances instead".

> Why do you need to know the number of instances. I know that Python
> does not support Class Variable, but you can always create a global
> variable and increase it whenever you add a new instance. this will
> keep a record for you of how many instances you have.

That's not what the Original Poster asked for, but there is a better way
than keeping a global variable. Make the counter a class attribute. That
way you don't have to increment the global, the class does its own

class CountedClass:
    count = 0
    def __init__(self, arg):
        self.__class__.count += 1
        self.arg = arg
    def __del__(self):
        self.__class__.count -= 1


>>> a = CountedClass(4)
>>> b = CountedClass(4)
>>> c = CountedClass(4)
>>> CountedClass.count
>>> a = 1
>>> CountedClass.count
>>> del b
>>> CountedClass.count
>>> L = [CountedClass(None) for i in range(1000)]
>>> CountedClass.count


More information about the Python-list mailing list