Home > Net >  Delete all instances of child classes when clearing container in parent class- Python OOP
Delete all instances of child classes when clearing container in parent class- Python OOP

Time:02-21

Aim-

To delete all the instances of child classes from the parent class

Background-

Example-

class Sprite:
    all = []
    def __init__(self):
        self.__class__.__bases__[0].all.append(self)

class Player(Sprite):
    def __init__(self):
        super().__init__()

class Enemy(Sprite):
    all = []
    def __init__(self):
        super().__init__()
        self.__class__.all.append(self)

class Projectile(Sprite):
    def __init__(self):
        super().__init__()

for i in range(3):
    Enemy()

Sprite.all.clear()
print(Enemy.all)
print(Sprite.all)

Result-

[<Enemy object at 0x1025bd580>, <Enemy object at 0x1025bd5b0>, <Enemy object at 0x1025bd070>]
[]

Required Result-

[]
[]

Question-

I could implement a method to delete all the instances of the child classes from the parent class iterating over Sprite.__subclasses__() but that would require creating a container for each child class, including Player and Projectile.

Is there an alternative way I could delete all the instances of the child classes from the parent class?

*I am using Python 3.8.9

CodePudding user response:

I have created a an static class method inside the parent class as mentioned below, which when invoked clears all the instances under it including the child ones.

class Sprite:
    all = []
    def __init__(self):
        self.__class__.__bases__[0].all.append(self)
    
    def __clear_all__():
        [x.all.clear() for x in Sprite.all]
        Sprite.all.clear()
    
class Player(Sprite):
    def __init__(self):
        super().__init__()

class Enemy(Sprite):
    all = []
    def __init__(self):
        super().__init__()
        self.__class__.all.append(self)

class Projectile(Sprite):
    def __init__(self):
        super().__init__()

for i in range(3):
    Enemy()

print(Sprite.__clear_all__())
print(Sprite.all)
print(Enemy.all)
  • Related