аватар question@mail.ru · 01.01.1970 03:00

Python method that displays all copies of his class

How to create a method in Python, which will display all copies of the same class in which this method is defined?

аватар answer@mail.ru · 01.01.1970 03:00

Here is the option in which the memory does not flow, and which supports the wrapping of several classes.

metaclass:

   Import  Weakref  class   mymeta  ( type ):   def   __ Init __  ( self, *args, ** kwargs ):  Self .__ Instances =}   super  (Maymeta, SELF) .__ Init __ (*args, ** kwargs)   def   get_instance  ( self ):   retu   line  (self .__ Instances.values ​​())   def   delete  ( Self, ID_INSTANCE ):   delf .__ Instances [id_instance]   def   __ Call __  ( self, *args, ** kwargs ):  Instance =  super  (Mymeta, Self) .__ call __ ( *args, ** kwargs)  self .__ Instances [ id  (Instance)] = Weakref.proxy (Instance)   retu  Instance    

use (you can create several such classes without copying methaclass):

   class   myclass  ( object , metaclass = Mymeta):   def   __ Del __  ( self ):  # This method and action inside it is required, ��Nach will flow memory to the proxy   Self .__ class __. Delete ( id  (self) (self) (self))   print  (myclass.get_instance ()) a = myclass () b = myclass ()   print  (Myclass.get_instances ())   Del  B  print  (Myclass.get_instance ())                                       

Latest

Similar