0

Suppose the following code:

class Person():
    def __init__(self,name):
        self.name = name

class Student(Person): pass

class Teacher(Person): pass

John = Student('John')
Tom = Student('Tom')
Victor = Teacher('Victor')

After the script is run, class Person is aware of its subclasses through

In [22]: Person.__subclasses__()
Out[22]: [__main__.Student, __main__.Teacher]

How to find all instances of class Student like:

Student.__instances__()
AttributeError: type object 'Student' has no attribute '__instances__'
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • 1
    Create a metaclass that automatically registers instances in `__new__` (preferably decorating any method the user defines). The reason I suggest a metaclass instead of using the parent class is that you will be able to do it on a per-class basis transparently to the user. Alternatively, you could probably use the garbage collector somehow probably. Both options are probably not what you want, the second one with extreme prejudice. – Mad Physicist May 21 '18 at 03:18
  • ty, could please transmit the comment to answer. @MadPhysicist – AbstProcDo May 21 '18 at 03:27
  • Also see https://stackoverflow.com/q/12101958/8033585 – AGN Gazer May 21 '18 at 03:36

0 Answers0