How would I track the amount of objects in a class that often adds and deletes objects?

Viewed 30

I have a code that often generates new objects and then deletes them sometimes, how would I find the amount of objects in the class at any given time?

How would I make it count up when I create an object and count down when I delete it?

class Enemy:
    def __init__(self, Name, MaxHp, Hp, Def, Atk, Stat, StatCd):

e1 = Enemy("Green Slimelet", 10, 10, 0, 3, "none", 0)
e2 = Enemy("Green Slime", 25, 25, 2, 8, "none", 0)
#Here i would put the counting thing
del e1
#Count again
1 Answers

You should keep a list of the Enemies, as @deceze has suggested.

class Enemy:
    def __init__(self, Name, MaxHp, Hp, Def, Atk, Stat, StatCd):
        pass


enemies = []

# Add an enemy
enemies.append(Enemy("Green Slimelet", 10, 10, 0, 3, "none", 0))
enemies.append(Enemy("Green Slime", 25, 25, 2, 8, "none", 0))

# Remove an enemy
enemies.pop(1) # Take note that index starts count from 0
# or
del enemies[0]

enemies_count = len(enemies)
Related