pretty basic instantiation question

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Oct 24 03:14:29 CEST 2006


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

[fixing top-posting]

> sittner at lkb.ens.fr 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
counting.


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


Example:

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



-- 
Steven 




More information about the Python-list mailing list