I run python code where i create multiple objects from 1 class and register these object in an IterRegistery:
class IterRegistry(type):
def __iter__(cls):
return iter(cls._registry)
class exampleclass(metaclass=IterRegistry):
_registry = []
def __init__(self, number):
self._registry.append(self)
self.number = number
def destroy(self):
if self.number == 1:
del self
exampleclass(1)
exampleclass(2)
for e in exampleclass:
e.destroy
Now i would like an object to delist itself from the registery and destroy itself from the inside out if several requirements are met. It tried to do this by using:
del self
But that's not working.
Is there a proper way to achieve this?
CodePudding user response:
Remove itsself from the _registry list and python will garbage collect it, and iterate over exampleclass
not IterRegistry
class IterRegistry(type):
def __iter__(cls):
return iter(cls._registry)
class exampleclass(metaclass=IterRegistry):
_registry = []
def __init__(self, number):
self._registry.append(self)
self.number = number
def destroy(self):
if self.number == 1:
self.__class__._registry.remove(self)
exampleclass(1)
exampleclass(2)
for e in exampleclass:
e.destroy()
However you don't need a metaclass:
class exampleclass():
_registry = []
def __init__(self, number):
self._registry.append(self)
self.number = number
def destroy(self):
if self.number == 1:
self.__class__._registry.remove(self)
@classmethod
def __iter__(cls):
return iter(cls._registry)
exampleclass(1)
exampleclass(2)
for e in exampleclass:
e.destroy()
or even:
class exampleclass():
registry = []
def __init__(self, number):
self._registry.append(self)
self.number = number
def destroy(self):
if self.number == 1:
self.__class__._registry.remove(self)
exampleclass(1)
exampleclass(2)
for e in exampleclass.registry:
e.destroy()